Zip in Python
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.
If you like my articles and find them useful, feel free to buy me a coffee. Thanks!
To get updates for my new stories, follow me on medium and twitter
Other articles:
- Beginner’s Guide to ReactJS
- The Journey of JavaScript: from Downloading Scripts to Execution
- Why Progressive Web Apps are great and how to build one
- Let’s get this ‘this’ once and for all
- Service Workers
- Service Workers implementation
- Execution Context in JavaScript
- Virtual DOM in ReactJS
- Prototypes in JavaScript
- ‘this’ in JavaScript
- Object.create in JavaScript
- Inheritance in JavaScript
- Create objects in JavaScript
- Objects in JavaScript
- Zip in Python
- decorators in Python
- Concatenating two lists in Python
- lambda, map, and filter in Python
- List comprehensions in Python
📝 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 >
