I want to add all elements from one list to another list:
list1 = ['hi', 'how', 'are', 'you', 'googl']
ok = ['item22']
list1 = list1.extend(ok)
print(list1)
But it prints None
. Why is that?
I want to add all elements from one list to another list:
list1 = ['hi', 'how', 'are', 'you', 'googl']
ok = ['item22']
list1 = list1.extend(ok)
print(list1)
But it prints None
. Why is that?
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.
Since it returns None
, you should not re-assign it back to the list variable.
You can do
list1 = ['hi', 'how', 'are', 'you', 'googl']
ok = ['item22']
list1.extend(ok)
Then when you print list1
it will print
['hi', 'how', 'are', 'you', 'googl', 'item22']
Using append
as mentioned below is the better way to add a single value to the end of a list.
list1 = ['hi', 'how', 'are', 'you', 'googl']
ok = 'item22' # Notice no brackets here
list1.append(ok)
There is another way, using module numpy will do the work https://pypi.org/project/numpy/
Specific in your example it will be look like this:
import numpy as np
list1 = ['hi','how','are','you','googl']
ok = ['item22']
list1 = list(np.append(list1, ok))
print(list1)