By Lenin Mishra
Why use zip?
zip() allows you to map the same index of multiple iterables.
Syntax of zip
Let’s look at an example.
x = [1, 2, 3] y = [4, 5, 6] mapping = zip(x, y) print(mapping)
If you run the above snippet, it will return you something like this.
<zip object at 0x1033d7d08>
As you can see, when you
print(mapping), it returns a
zip object. This is an iterator object that consists of
tuples. To check out its contents, let’s convert it to a list.
This snippet produces the following result.
[(1, 4), (2, 5), (3, 6)]
Now how to unzip? You can do that with the
* operator. Let’s convert our
mapping variable back to its components.
x,y = zip(*mapping) print(x) print(y)
This in turn assigns tuples to
(1, 2, 3) # Value of x (4, 5, 6) # Value of y
As I mentioned earlier, zip() creates an iterator of tuples. Therefore when we unpack, we get our x and y values back as tuples. You can use the
list() method to convert them back to lists.
Solve a competitive interview question
Write a function to map all elements of the same index for the following list.
input_lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] output_lst = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
The function should take in the
input_lst and return the
If you are able to solve it, make sure to comment below.