Why does my simple python list get reset to None in a for loop?
Question:
I was encountering a bug in a large program that I have managed to isolate to a simpler problem. I am trying to append a list
kk=0
flist=[]
for key in range(5):
if kk==0:
flist=['w']
else:
print "flist*x*", flist
flist=flist.append('s')
kk=kk+1
In other words, in the first iteration when kk =0, the list should have been initialized and then subsequently appended. However, I get the error:
flist=flist.append('s')
AttributeError: 'NoneType' object has no attribute 'append'
I am using python 2.7
Answers:
The return value of list.append
is None
. Python adds the element directly to the list object it is called upon. You just need to call the function not assign to its return value:
flist.append('s')
I was encountering a bug in a large program that I have managed to isolate to a simpler problem. I am trying to append a list
kk=0
flist=[]
for key in range(5):
if kk==0:
flist=['w']
else:
print "flist*x*", flist
flist=flist.append('s')
kk=kk+1
In other words, in the first iteration when kk =0, the list should have been initialized and then subsequently appended. However, I get the error:
flist=flist.append('s')
AttributeError: 'NoneType' object has no attribute 'append'
I am using python 2.7
The return value of list.append
is None
. Python adds the element directly to the list object it is called upon. You just need to call the function not assign to its return value:
flist.append('s')