In Python Shell, I entered:
JavaScript
x
4
1
aList = ['a', 'b', 'c', 'd']
2
for i in aList:
3
print(i)
4
and got
JavaScript
1
5
1
a
2
b
3
c
4
d
5
but when I tried:
JavaScript
1
5
1
aList = ['a', 'b', 'c', 'd']
2
aList = aList.append('e')
3
for i in aList:
4
print(i)
5
and got
JavaScript
1
5
1
Traceback (most recent call last):
2
File "<pyshell#22>", line 1, in <module>
3
for i in aList:
4
TypeError: 'NoneType' object is not iterable
5
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.