Zip in Python

An Extensive Guide To Progressive Web Applications

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.

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.

zip truncates the extra elements of list_b in the output.

zip always creates the tuple in the order of iterbales 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.


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:

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.

Other articles:

An Extensive Guide To Progressive Web Applications

  1. Let’s get this ‘this’ once and for all
  2. Service Workers
  3. Service Workers implementation
  4. Decorators in Python
  5. lambda, map and filter in Python
  6. Concatenating two lists in Python
  7. List comprehensions in Python