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?
Advertisement
Answer
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.