The built-in zip()
function aggregates elements from two or more iterables, creating an iterator that yields tuples. Each tuple contains the i-th element from each of the input iterables. The function stops when the shortest iterable is exhausted, ensuring that each tuple is complete:
zip()
Signature Arguments Argument Description Default Value *iterables
One or more iterables (e.g., lists, tuples, strings) to be zipped together. Required arguments strict
A Boolean that, if set to True
, raises a ValueError
if iterables have different lengths. False
Return Value
zip()
Examples
With two iterables as arguments:
With more than two iterables:
With a single iterable:
With no arguments:
zip()
Common Use Cases
The most common use cases for the zip()
function include:
*
).zip()
Real-World Example
Suppose you have three lists, one containing product names and the others containing their respective prices and stocks. You want to create a dictionary that maps product names to total costs. Here’s how you can do it with the zip()
function:
In this example, you use zip()
to iterate over the products, prices, and stocks in parallel using a for
loop. Then, you construct the desired dictionary by using the products as keys and multiplying the stocks and prices.
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4