Zip two lists of lists in Python

The zip function of Python is used to map a similar index element of the different containers (iterable). This function returns an iterator of tuples in the form of an object. If multiple iterators are passes, then the function will return an iterator of tuples. This iterator of tuples consists of the tuples having element of each iterator having similar index values.

For example,

Input:
A = [1,2,3,4]
B = [5,6,7,8]

Output:
[[1,5], [2,6], [3,7], [4,8]]

In the above example, there are two lists A, B. Through zipping, we got a new list consisting of the lists having elements at the of both the lists having the same indexes.

1. map(list.__add__): 

Zipping of two lists can be done with the help of map function in Python. __add__ is the magic method of addition operator so it is used to adding the two instances of a custom object.

Example 1:

See the example below using zip() function:

# Python program of zipping lists of list
# declare two list
list1 = [[1, 2],[3, 4]]
list2 = [['c', 'o'], ['d', 'e']]

# map(list.__add__)
print(list(map(list.__add__, list1, list2)))

Output:

[[1, 2, 'c', 'o'], [3, 4, 'd', 'e']]

Example 2:

# Python program of zipping lists of list
# declare two list
#list1 having more elements than list2
list1 = [[1, 2],[3, 4], [5, 6]]
list2 = [['c', 'o'], ['d', 'e']]

# map(list.__add__)
print(list(map(list.__add__, list1, list2)))

Output:

[[1, 2, 'c', 'o'], [3, 4, 'd', 'e']]

2. Using itertools.chain and zip():

Itertools.chain creates an iterator that returns each element from the first list, and when it gets complete then it will move the next list. While the zip() is going to use for zipping the two lists.

Example:

# Python program of zipping lists of list
#import itertools
import itertools

# declare the lists
list1 = [['s','p'], ['e', 'e'], ['d', 'y']]
list2 = [[1,2,3], [4,5,6], [7,8,9]]
# itertools.chain() and zip() function
[list(itertools.chain(*i)) for i in zip(list1, list2)]

Output:

[['s', 'p', 1, 2, 3], ['e', 'e', 4, 5, 6], ['d', 'y', 7, 8, 9]]

3. Using sum() function and zip() function:

The zip() function will zip the elements of both the lists while sum() function will sum the pair of elements of the zipped list.

# Python program of zipping lists of list
# declare the lists
list1 = [['s','p'], ['e', 'e'], ['d', 'y']]
list2 = [[1,2,3], [4,5,6], [7,8,9]]

# sum() function and zip() function
[sum(i,[]) for i in zip(list1,list2)]

Output:

[['s', 'p', 1, 2, 3], ['e', 'e', 4, 5, 6], ['d', 'y', 7, 8, 9]]

Leave a Reply

Your email address will not be published. Required fields are marked *