Appending Turns My List to Nonetype

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



Leave a reply



Submit