Extending List Returns None

Extending list returns None

The function extend is an in-place function i.e. It will make the changes to the original list itself. From the docs

Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

Hence you do not need to re-assign it back to the list variable.

You can do

list1 = ['hi','how','are','you','googl']
ok = 'item22'
list1.extend([ok]) # Notice brackets here

Then when you print list it will print

['hi','how','are','you','googl','item22']

Better way

Using append as mentioned below is the better way to do it.

list1 = ['hi','how','are','you','googl']
ok = 'item22'
list1.append(ok) # Notice No brackets here

Why when I extend a list does it have 'NoneType' as type?

extend, like many other list operations, operates in-place and returns None. ListA is modified with the extra elements.

Unexpected Behavior of Extend with a list in Python

The extend() method appends to the existing array and returns None. In your case, you are creating an array — [4, 5, 6] — on the fly, extending it and then discarding it. The variable b ends up with the return value of 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"]

Python - Extending a list directly results in None, why?

list.extend modifies the list in place and returns nothing, thus resulting in None. In the second case, it's a temporary list that is being extended which disappears immediately after that line, while in the first case it can be referenced via x.

to append a listB to a listA while trying to extend listC to listB.

Instead of using extend, you might want to try this:

listA.append(listB[15:18] + listC[3:12])

Or do it in multiple simple lines with extend if you want to actually modify listB or listC.



Related Topics



Leave a reply



Submit