Why Does List.Append() Return None

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?.

Python's insert returning None?

Mutating-methods on lists tend to return None, not the modified list as you expect -- such metods perform their effect by altering the list in-place, not by building and returning a new one. So, print numbers instead of print clean will show you the altered list.

If you need to keep numbers intact, first you make a copy, then you alter the copy:

clean = list(numbers)
clean.insert(3, 'four')

this has the overall effect you appear to desire: numbers is unchanged, clean is the changed list.

Python Append to a list returns none

append does not return anything, so you cannot say

ListB = ListB.append('New_Field_Name')

It modifies the list in place, so you just need to say

ListB.append('New_Field_Name')

Or you could say

ListB += ['New_Field_Name']

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 return is returning 'None' instead the of required 'List'?

Because you are not printing the list, you are just returning it (the list object itself). This op(a) is appropriate if you want to do something with the list, but if you just want to print its content you should call print(op(a)) or change the op function to print the contents of the list instead of returning it.



Related Topics



Leave a reply



Submit