154
What is zip() in Python?
In Python, the zip()
function is a built-in function that takes iterables as input and returns an iterator of tuples. Each tuple contains elements from the corresponding position of the input iterables.
Syntax:
zip(*iterables)
Parameters:
- iterables: One or more iterables (like lists, tuples, strings, or dictionaries).
Return Value:
- An iterator of tuples, where each tuple contains elements from the corresponding position of the input iterables.
Example:
Python
fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "green"]
zipped_data = zip(fruits, colors)
print(list(zipped_data))
Output:
[('apple', 'red'), ('banana', 'yellow'), ('cherry', 'green')]
Explanation:
- We have two lists:
fruits
andcolors
. - The
zip()
function is called with these lists as arguments. - It creates an iterator of tuples, where each tuple contains an element from
fruits
and an element fromcolors
at the same position. - We convert the iterator to a list using
list()
to print the result.
Key Points:
- The
zip()
function stops when the shortest iterable is exhausted. - If the iterables have different lengths, the remaining elements in the longer iterables are ignored.
- To create tuples of a specific length, you can use the
fillvalue
argument of thezip()
function.
Example with fillvalue
:
Python
fruits = ["apple", "banana"]
colors = ["red", "yellow", "green"]
zipped_data = zip(fruits, colors, fillvalue="unknown")
print(list(zipped_data))
Output:
[('apple', 'red'), ('banana', 'yellow'), ('unknown', 'green')]
Common Use Cases:
- Iterating over multiple sequences simultaneously.
- Creating dictionaries from lists of keys and values.
- Transposing matrices.
- Unpacking multiple sequences into separate variables.