views:

57

answers:

1

In Python Shell, I entered:

aList = ['a', 'b', 'c', 'd']  
for i in aList:  
    print(i)

and got

a  
b  
c  
d  

but when I tried:

aList = ['a', 'b', 'c', 'd']  
aList = aList.append('e')  
for i in aList:  
    print(i) 

and got

Traceback (most recent call last):  
  File "<pyshell#22>", line 1, in <module>  
    for i in aList:  
TypeError: 'NoneType' object is not iterable  

Does anyone know what's going on? How can I fix/get around it?

+5  A: 

list.append is a method that modifies the existing list. It doesn't return a new list -- it returns None, like most methods that modify the list. Simply do aList.append('e') and your list will get the element appended.

Thomas Wouters
And since it doesn't return anything, you're setting aList to None if you do do the assignment, which is why you're getting the error.
kindall
All functions return something :)
Thomas Wouters
@Thomas, true - but sometimes that *something* is `None`. But is `None` really something? My head hurts!
Mark Ransom
@kindall: "doesn't return anything" should be "in effect, it's the same is if the method doesn't have a `return` statement and returns `None` implicitly". And. "Methods which mutate an object almost never return a value, pop is the notable exception."
S.Lott
@Thomas: You are technically correct... the best kind of correct!
kindall