Sitemap

Zip in Python

3 min readMay 5, 2017

zip takes n number of iterables and returns a list of tuples. the 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 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 lists.

Example:

Zip in Python3

In Python3, zip method 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 that delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations (Wikipedia definition).

Iterators return only one 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 its 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 an empty list.

📝 Read this story later in Journal.

🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: Get the noteworthy newsletter >

--

--

Rupesh Mishra
Rupesh Mishra

Written by Rupesh Mishra

Backend Developer | Freelance Blogger