Tuesday, August 8, 2017

zip in Python

In this post I am going to talk about ZIP. ZIP is a function that takes elements from multiple iterables and aggregates them into one where we basically share the index value. Let’s take the following example:
x = [1, 2, 3, 4, 5, 6]
y = [11, 22, 33, 44, 55, 66]
z = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
##Let’s go ahead and combine x, y. 
for a, b in zip(x, y):
    print(a, b)
"""
1 11
2 22
3 33
4 44
5 55
6 66
"""
##We can also do multiple elements.
for a, b, c in zip(x, y, z):
    print(a, b, c)
"""
1 11 a
2 22 b
3 33 c
4 44 d
5 55 e
6 66 f
"""
##zip(x, y, z) is a zip object. And we can iterate through the zip object. 
for i in zip(x, y, z):
    print(i)    
"""
(1, 11, 'a')
(2, 22, 'b')
(3, 33, 'c')
(4, 44, 'd')
(5, 55, 'e')
(6, 66, 'f')
"""
##We can also convert zip object to dictionary.
print(dict(zip(z, x)))
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
##We can also combine zip into list comprehension
[(a, b, c) for a, b, c in zip(x, y, z)]
"""
[(1, 11, 'a'),
 (2, 22, 'b'),
 (3, 33, 'c'),
 (4, 44, 'd'),
 (5, 55, 'e'),
 (6, 66, 'f')]
"""

No comments:

Post a Comment