ExampleEdit & Run
#Use the zip() Function

L1 = [1, 2, 3]
L2 = ["Python", "Java", "PHP"]

print(list(zip(L1, L2)))
copy
Output:
[(1, 'Python'), (2, 'Java'), (3, 'PHP')] [Finished in 0.01059895008802414s]

The zip() function is used to combine two or more iterables into an iterator of tuples, where each tuple contains the elements in the corresponding indices of the iterables. All the elements in a given index are combined into one tuple. 

Syntax

zip(*iterables)
copy

The function takes in an arbitrary number of iterables and returns an iterator of tuples.

For example, given two lists, the zip() function can be used to pair elements index-wise.

ExampleEdit & Run
list1 = ['a','b','c']
list2 = [1,2,3]
iter_result = zip(list1, list2)
result = list(iter_result)
print(result)
copy
Output:
[('a', 1), ('b', 2), ('c', 3)] [Finished in 0.010637523606419563s]

The for loop equivalent of the above program is as shown below.

ExampleEdit & Run
list1 = ['a','b','c']
list2 = [1,2,3]
result = []
for i, v in enumerate(list1):
    result.append((v, list2[i]))

print(result)
copy
Output:
[('a', 1), ('b', 2), ('c', 3)] [Finished in 0.010659686289727688s]

Example with three elements:

ExampleEdit & Run
L1 = [1, 2, 3, 4]
L2 = [10, 20, 30, 40]
L3 = [100, 200, 300, 400]
zipped = zip(L1, L2, L3)
print(list(zipped))
copy
Output:
[(1, 10, 100), (2, 20, 200), (3, 30, 300), (4, 40, 400)] [Finished in 0.010161678306758404s]

If the given iterables are not of equal length, the zip function zips the elements up to the length of the smallest one. 

ExampleEdit & Run
L1 = [1, 2, 3]
L2 = [10, 20, 30, 40]
L3 = [100, 200, 300, 400, 500]
zipped = zip(L1, L2, L3)
print(list(zipped))
copy
Output:
[(1, 10, 100), (2, 20, 200), (3, 30, 300)] [Finished in 0.0099718626588583s]

More Examples:

ExampleEdit & Run
countries = ('China', 'Rwanda', 'Canada', 'Philippines', 'Finland')
cities = ('Beijing', 'Kigali', 'Ottawa', 'Manilla', 'Helsinki')
zipped = zip(cities, countries)
print(list(zipped))

print('----------------------------------------')

a = [i for i in range(10)]
b = [i for i in range(10, 20)]
c = [i for i in range(20, 30)]
d = [i for i in range(30, 40)]
zipped = zip(a, b, c, d)
print(list(zipped))


copy
Output:
[('Beijing', 'China'), ('Kigali', 'Rwanda'), ('Ottawa', 'Canada'), ('Manilla', 'Philippines'), ('Helsinki', 'Finland')] ---------------------------------------- [(0, 10, 20, 30), (1, 11, 21, 31), (2, 12, 22, 32), (3, 13, 23, 33), (4, 14, 24, 34), (5, 15, 25, 35), (6, 16, 26, 36), (7, 17, 27, 37), (8, 18, 28, 38), (9, 19, 29, 39)] [Finished in 0.009680330753326416s]