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

Asked By: wander95

||

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')
Answered By: Farmer Joe
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.