Appending turns my list to NoneType
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.
Why does appending to a list raise a NoneType error in Python?
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(" ")]
Why does append() always return None in Python?
append
is a mutating (destructive) operation (it modifies the list in place instead of of returning a new list). The idiomatic way to do the non-destructive equivalent of append
would be
>>> l = [1,2,3]
>>> l + [4]
[1,2,3,4]
>>> l
[1,2,3]
to answer your question, my guess is that if append
returned the newly modified list, users might think that it was non-destructive, ie they might write code like
m = l.append("a")
n = l.append("b")
and expect n
to be [1,2,3,"b"]
Why does list.append() return None?
Just replace a_list = a_list.append(r)
with a_list.append(r)
.
Most functions, methods that change the items of sequence/mapping does return None
: list.sort
, list.append
, dict.clear
...
Not directly related, but see Why doesn’t list.sort() return the sorted list?.
appending list in python but get none as a result
e
and f
will always be None
because append()
does not return a value. Move your last append out of the print()
and just print(a)
Related Topics
What Is the Pythonic Way to Avoid Default Parameters That Are Empty Lists
Plotting Dates on the X-Axis with Python's Matplotlib
How to Add a New Column to a CSV File
How to Take a Screenshot/Image of a Website Using Python
How to Make Sure If Some HTML Elements Are Loaded for Selenium + Python
Change the Color of Text Within a Pandas Dataframe HTML Table Python Using Styles and CSS
How to Find Tag with Particular Text with Beautiful Soup
How to Find All Comments with Beautiful Soup
How to Exit Linux Terminal Using Python Script
How to Use Python2.7 Pip Instead of Default Pip
How to Use the Same Python Virtualenv on Both Windows and Linux
What Is Different Between Makedirs and Mkdir of Os
How to Execute Python File in Linux
Convert Unicode to Ascii Without Errors in Python
Why Is a List Comprehension So Much Faster Than Appending to a List
Pandas: Convert Categories to Numbers
Why Do We Use _Init_ in Python Classes
Why Are Packages Installed Rather Than Just Linked to a Specific Environment