zip takes n number of iterables and returns list of tuples. ith element of the tuple is created using the ith element from each of the iterables.
list_a = [1, 2, 3, 4, 5]
list_b = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
zipped_list = zip(list_a, list_b)
print zipped_list # [(1, ‘a’), (2, ‘b’), (3, ‘c’), (4, ‘d’), (5, ‘e’)]
zipped_list is a list of tuples where ith tuple i.e (1, ‘a’) is created using the ith element of list_a i.e 1 and ith element of list_b i.e ‘a’
If the length of the iterables are not equal, zip creates the list of tuples of length equal to the smallest iterable.
list_a = [1, 2, 3]
list_b = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
zipped_list = zip(list_a, list_b)
print zipped_list # [(1, ‘a’), (2, ‘b’), (3, ‘c’)]
zip truncates the extra elements of list_b in the output.
zip always creates the tuple in the order of iterables from left to right. list_a will always be before list_b in the output tuples
Unzip a list of tuples
To unzip a list of tuples we zip(*listP_of_tuples). Unzip creates separate list.
Example:
zipper_list = [(1, ‘a’), (2, ‘b’), (3, ‘c’)]
list_a, list_b = zip(*zipper_list)
print list_a # (1, 2, 3)
print list_b # (‘a’, ‘b’, ‘c’)
Zip in Python3
In Python3, zip methods returns a zip object instead of a list. This zip object is an iterator. Iterators are lazily evaluated.
Lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations (Wikipedia definition).
Iterators returns only element at a time. len function cannot be used with iterators. We can loop over the zip object or the iterator to get the actual list
Consider the below example:
list_a = [1, 2, 3]
list_b = [4, 5, 6]
zipped = zip(a, b) # Output: Zip Object. <zip at 0x4c10a30>
len(zipped) # TypeError: object of type ‘zip’ has no len()
zipped[0] # TypeError: ‘zip’ object is not subscriptable
list_c = list(zipped) #Output: [(1, 4), (2, 5), (3, 6)]
list_d = list(zipped) # Output []… Output is empty list becuase by the above statement zip got exhausted.
x,y=zip(*list_c)
print (x,y) # Output : (1, 2, 3) (4, 5, 6)
In the above example, zipped is a zip object which is an iterator. Using len function or accessing it’s element by index gives type error.
We convert the zip object to a list by list(zipped). After this we can use all the methods of list.
Iterators can be evaluated only time. After that they get exhausted, hence list_d output is empty list.