Python’s zip() function

In this tutorial, we will discuss a few important things about Python’s zip() function. Here, we consider Python3.
The zip() function takes iterables (can be zero or more), aggregates them in a tuple and returns it.
The syntax of the zip() function is: zip(iterables)
At first, we create an iterator object using zip().
numbers = list(range(5)) # list of numbers
letters = ['a', 'b', 'c', 'd', 'e'] # list of numbers# Create an iterator object using zip()
zipped = zip(numbers, letters)# Print the type of zipped
print('Type of zipped is: {}'.format(type(zipped)))
The output of the above print function is as follows:
Type of zipped is: <class 'zip'>
Now, we create a list of tuples from this zipped object.
# Create a list of tuples from zipped object
zipped_list = list(zipped)# Print the list of tuples
print('List of tupples is: {}'.format(zipped_list))
The output of the above print function is as follows:
List of tupples is: [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
Parallel loop using zip()
Parallel for loop using zip() can be achieved as follows:
for num, lett in zip(numbers, letters):
print(num, lett)
The output of the above print function is as follows:
0 a
1 b
2 c
3 d
4 e
Unzipping
A list of tuples can be unzipped using zip() with an unpacking operator *.
pairs = [(0,'x'), (1, 'y'), (2, 'z')] # list of tupples# use unpacking operator * to unzip the data
nums, alphabets = zip(*pairs)# Print the outputs
print(nums)
print(alphabets)
The outputs of the above two print functions are as follows:
(0, 1, 2)
('x', 'y', 'z')
Note that both the outputs are tuples.
This tutorial was initially posted at http://soumenatta.blogspot.com/.