Python Append to a list returns none

Question:

I know different versions of this question has been answered for example [here].1 But I just couldn’t seem to get it working on my example. I am trying to make a copy of ListA called ListB and then add an additional item to ListB i.e. ‘New_Field_Name’ in which later on I use as column headers for a dataframe.

Here is my code:

ListA = ['BUSINESSUNIT_NAME' ,'ISONAME', 'Planning_Channel', 'Planning_Partner', 'Is_Tracked', 'Week', 'Period_Number']
print type(ListA)

Output:

ListB = list(ListA)
print '######', ListB, '#####'

Output:
###### [‘BUSINESSUNIT_NAME’, ‘ISONAME’, ‘Planning_Channel’, ‘Planning_Partner’, ‘Is_Tracked’, ‘Week’, ‘Period_Number’] #####

ListB = ListB.append('New_Field_Name')
print type(ListB)
print ListB

Output:

None

Asked By: IcemanBerlin

||

Answers:

append does not return anything, so you cannot say

ListB = ListB.append('New_Field_Name')

It modifies the list in place, so you just need to say

ListB.append('New_Field_Name')

Or you could say

ListB += ['New_Field_Name']
Answered By: Cory Kramer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.