Python Append to a list returns none [duplicate]

眉间皱痕 提交于 2019-12-20 07:39:40

问题


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


回答1:


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']


来源:https://stackoverflow.com/questions/28110161/python-append-to-a-list-returns-none

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!