In this notebook, we will go through the following topics
Join / Merge two lists in python using + operator.
Join / Merge two lists in python using list.extend().
Join / Merge two lists in python using unpacking.
Join / Merge two lists in python using itertools.
Join / Merge two lists in python using for loop.
Let us create random list of numbers using Python random module.
import random
random.seed(4)
l1 = random.sample(range(0, 9), 5)
l2 = random.sample(range(0, 9), 5)
print(l1)
print(l2)
We can use + operator in Python to add two or more lists as long as the lists are of same type.
l1 + l2
print(l1)
print(l2)
We can use the '+' operator on list of characters or strings too.
l1 = 'john ludhi'.split(' ')
l1
l2 = 'elon musk'.split(' ')
l2
l1 + l2
import random
random.seed(4)
l1 = random.sample(range(0, 9), 5)
l2 = random.sample(range(0, 9), 5)
print(l1)
print(l2)
l1.extend(l2)
Let us print list l1
print(l1)
We can use list.extend() method on list of strings or characters too.
l1 = 'john ludhi'.split(' ')
l2 = 'elon musk'.split(' ')
print(l1)
print(l2)
l1.extend(l2)
print(l1)
l1 = 'john ludhi'.split(' ')
l2 = 'elon musk'.split(' ')
mergelist = [*l1, *l2]
mergelist
import random
random.seed(4)
l1 = random.sample(range(0, 9), 5)
l2 = random.sample(range(0, 9), 5)
print(l1)
print(l2)
mergelist = [*l1, *l2]
print(mergelist)
We can use iterools module to chain two or more lists in Python
iterools.chain(list1,list2,...)
import random
random.seed(4)
l1 = random.sample(range(0, 9), 5)
l2 = random.sample(range(0, 9), 5)
import itertools
result = itertools.chain(l1,l2)
result
We can go through the above chain using for loop
import itertools
for l in itertools.chain(l1,l2):
print(l)
Or we can convert in to a Python list.
list(itertools.chain(l1,l2))
We can chain multiple lists too with itertools.chain()
list(itertools.chain(l1,l2,l2))
import random
random.seed(4)
l1 = random.sample(range(0, 9), 5)
l2 = random.sample(range(0, 9), 5)
print(l1)
print(l2)
for elem in l2:
l1.append(elem)
print(l1)
To learn more about Python append, checkout following notebook
https://www.nbshare.io/notebook/767549040/Append-In-Python/