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
Thread Safety in Python's Dictionary
Cannot Pass an Argument to Python with "#!/Usr/Bin/Env Python"
Get Contents of a Tkinter Entry Widget
How to Modify Variable in Python That Is in Outer, But Not Global, Scope
Pandas Dataframe Concat VS Append
2D List Has Weird Behavor When Trying to Modify a Single Value
Plotting Grouped Data in Same Plot Using Pandas
How to Determine the Length of Lists in a Pandas Dataframe Column
Make Requests Using Python Over Tor
Extract Number from String in Python
Use Python's String.Replace VS Re.Sub
Concatenate Numpy Arrays Without Copying
How to Capture Output of Python's Interpreter and Show in a Text Widget