Appending turns my list to NoneType

Viewed 72068

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?

4 Answers

Sometimes this error appears when you forgot to return a function at the end of another function and passed an empty list, interpreted as NoneType.

from this:

def func1():
  ...
  func2(empty_list)

def func2(list):
  ...
  # use list here but it interpreted as NoneType

to this:

def func1():
  ...
  return func2(empty_list)
    
def func2(list):
  ...
  # use list here, it will be interpreted as an empty List
Related