The zip function
The zip
function creates an iterator that combines elements from sequences (lists, tuples, sets). The function returns an iterator in which all elements of the first and second sequences are merged together in order. In the function parameter, we specify all the tuples, lists, sets, etc. that interest us.
Syntax
zip(first sequence, second sequence and so on.)
Example
Let's use the zip
function to make a new tuple based on the two original ones:
tlp1 = ('a', 'b', 'c')
tlp2 = (1, 2, 3)
res = zip(tlp1, tlp2)
print(tuple(res))
Result of code execution:
(('a', 1), ('b', 2), ('c', 3))
Example
Now let's use the zip
function to make a new tuple based on two lists:
lst1 = ['d', 'e', 'f']
lst2 = [4, 5, 6]
res = zip(lst1, lst2)
print(tuple(res))
Result of code execution:
(('d', 4), ('e', 5), ('f', 6))
Example
Let's create a tuple from two sets:
st1 = {'a', 'b', 'c'}
st2 = {'d', 'e', 'f'}
res = zip(st1, st2)
print(tuple(res))
Result of code execution:
(('a', 'd'), ('c', 'e'), ('b', 'f'))
Example
Now let's create a tuple of three sets:
st1 = {'a', 'b', 'c'}
st2 = {'d', 'e', 'f'}
st3 = {1, 2, 3}
res = zip(st1, st2, st3)
print(tuple(res))
Result of code execution:
(('c', 'f', 1), ('b', 'd', 2), ('a', 'e', 3))
Example
The zip
function allows you to iterate over multiple objects at once. Let's iterate over three lists as an example:
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
lst3 = [7, 8, 9]
for el1, el2, el3 in zip(lst1, lst2, lst3):
print(el1, el2, el3)
Result of code execution:
1 4 7
2 5 8
3 6 9