Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending turns my list to NoneType

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?

like image 528
user460847 Avatar asked Oct 01 '10 15:10

user460847


People also ask

Why is Python saying my list is NoneType?

In general, the error means that you attempted to index an object that doesn't have that functionality. You might have noticed that the method sort() that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

Why is my append returning None?

append() is an in-place operation, meaning that it modifies the state of the list , instead of returning a new list object. All functions in Python return None unless they explicitly return something else. The method a. append() modifies a itself, which means that there's nothing to return.

How do I fix NoneType in Python?

The error “TypeError: 'NoneType' object is not iterable” occurs when you try to iterate over a NoneType object. Objects like list, tuple, and string are iterables, but not None. To solve this error, ensure you assign any values you want to iterate over to an iterable object.


2 Answers

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.

like image 102
Thomas Wouters Avatar answered Sep 20 '22 05:09

Thomas Wouters


Generally, what you want is the accepted answer. But if you want the behavior of overriding the value and creating a new list (which is reasonable in some cases^), what you could do instead is use the "splat operator", also known as list unpacking:

aList = [*aList, 'e'] #: ['a', 'b', 'c', 'd', 'e'] 

Or, if you need to support python 2, use the + operator:

aList = aList + ['e'] #: ['a', 'b', 'c', 'd', 'e'] 

^ There are many cases where you want to avoid the side effects of mutating with .append(). For one, imagine you want to append something to a list you've taken as a function argument. Whoever is using the function probably doesn't expect that the list they provided is going to be changed. Using something like this keeps your function "pure" without "side effects".

like image 44
SCB Avatar answered Sep 24 '22 05:09

SCB