Home » »

# How to Merge / Join Two or more Lists

|| 0

How to Merge / Join Two or more Lists
Stechies

There are many ways to join / merge / flatten a list of lists. This can be done either using nested loops, custom function, chain() function, + operator, extend() function.

## Loop

Example

``````List1=[[1,2],[3,4,5],[6,7,8,9]]
flat=[]
for a in List1:
for b in a:
flat.append(b)
print (flat)``````

Output:

``[1, 2, 3, 4, 5, 6, 7, 8, 9]``

## Custom Function

One more method is to use a generator function to yield an iterator and produce to a list. In this, we define a function along with the loop inside the function and appending all elements into a list.

Example

``````def flatlist(list):
for a in list:
for b in a:
yield b
List=[[1,2,3],[4,5],[6,7,10,9]]
flat=flatlist(List)
print (list(flat))``````

Output:

``[1, 2, 3, 4, 5, 6, 7, 10, 9]``

## Chain() Function

Using chain() method from itertools module it is a compact method. This method will add the list at end of first one.

Example

``````List=[[1,2,3],[4,5],[6,7,10,9]]
import itertools
flat=itertools.chain.from_iterable(List)
print (list(flat))``````

Output:

``[1, 2, 3, 4, 5, 6, 7, 10, 9]``

## "+" Operator

Using the "+" operator, we can join/merge two lists. Here we going to add two list of strings.

Example

``````# List of strings
list1 = ["This" , "is", "a", "example", "to add "]
# List of string
list2 = ["This" , "is", "from ", "second ", "list to add "]

# Merge two lists
# List of strings
list1 = ["This" , "is", "a", "sample", "program"]
list2 = ["This" , "from ", "second ", "list to add "]
finalList = list1 + list2
print "final list of strings", finalList``````

Output:

``final list of strings ['This', 'is', 'a', 'sample', 'program', 'This', 'from ', 'second ', 'list to add ']``

## extend() Method

Concatenating a list and to extend an existing list, we can achieve this using extend() method. You can use any type of list like integer, here we are using strings list.

Example

``````# List of strings
list1 = ["This" , "is", "a", "example", "to add "]
# List of string
list2 = ["This" , "is", "from ", "second ", "list to add "]

# Merge two lists
# List of strings
list1 = ["This" , "is", "a", "sample", "program"]
list2 = ["This" , "from ", "second ", "list to add "]
list1.extend(list2)
print ("final list of strings"), list1``````

Output

``final list of strings ['This', 'is', 'a', 'sample', 'program', 'This', 'from ', 'second ', 'list to add ']``