22

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Bob Ebert
  • 1,342
  • 4
  • 22
  • 41

2 Answers2

35

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']
Better way

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)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
5

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)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65