Why does appending to a list raise a NoneType error in Python?

Question:

Here is my code:

text="""col1 col2 col3
a 1 $
b 2 @
c 3 &
"""
mList = []
for line in text.splitlines():
    for item in line.split(" "):
        mList = mList.append(item)

This raises an error, 'NoneType' object has no attribute 'append'. I’ve tried other ways of creating the list and doing this, but the best I get is the list turned to None. What’s going on here?

Asked By: X-Mann

||

Answers:

list.append does not return (= returns None), but just append the item into the list.

>>> lst = []
>>> return_value_of_append = lst.append('something')
>>> return_value_of_append is None
True

So the following line make the mList become None:

mList = mList.append(item)

Replacing the above line with the following solve the issue:

mList.append(item)
Answered By: falsetru

list.append() is an in-place method, it does not return anything ( and hence by default it returns None , as all function calls must return some value, and if some function does not explicitly return anything, the call returns `None).

Hence, when you assign it back to mList, it becomes None and in the next iteration when you do – mList.append() , it errors out as mList is None.

You should try –

mList.append(item)

Or you can simply do what you are trying to do in a list comprehension –

mList = [item for line in text.splitlines() for item in line.split(" ")]
Answered By: Anand S Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.