🐍 Python Q41 / 170

What is zip() function?

AI-Powered Answer ✓ Answered

The `zip()` function in Python is a built-in function that aggregates elements from multiple iterables (like lists, tuples, or strings) into a single iterator. It returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables.

What `zip()` Does

The primary purpose of zip() is to pair up elements from two or more iterables based on their index. For example, if you have two lists, zip() will take the first element from the first list and the first element from the second list and form a tuple. It continues this process for all elements, creating an iterator of these tuples.

Basic Syntax

python
zip(*iterables)

Where *iterables means one or more iterable objects.

Example 1: Zipping Two Lists

This example demonstrates how zip() combines elements from two lists into an iterator of tuples. We then convert it to a list for display.

python
names = ['Alice', 'Bob', 'Charlie']
ages = [30, 24, 28]

zipped_data = zip(names, ages)
print(list(zipped_data))
# Output: [('Alice', 30), ('Bob', 24), ('Charlie', 28)]

Example 2: Zipping with Different Lengths

An important characteristic of zip() is that it stops aggregating elements once the shortest iterable is exhausted. Elements from longer iterables beyond that point are ignored.

python
numbers = [1, 2, 3, 4, 5]
letters = ['a', 'b', 'c']

zipped_result = zip(numbers, letters)
print(list(zipped_result))
# Output: [(1, 'a'), (2, 'b'), (3, 'c')]

Unzipping with `*` Operator

The * operator can be used with zip() to perform the reverse operation, often referred to as 'unzipping'. It unpacks an iterable of iterables into separate arguments for zip().

python
coordinates = [('x1', 10), ('x2', 20), ('x3', 30)]

var_names, values = zip(*coordinates)

print(list(var_names))
# Output: ['x1', 'x2', 'x3']
print(list(values))
# Output: [10, 20, 30]

Common Use Cases

  • Iterating over multiple lists simultaneously: For example, when processing data points and their corresponding labels.
  • Creating dictionaries: By zipping two lists, one for keys and one for values, you can easily create a dictionary.
  • Transposing matrices: Although not its primary purpose, zip(*matrix) can transpose a 2D list (matrix).
  • Combining related data: Useful for any scenario where you need to pair up corresponding items from different collections.

Important Considerations

  • zip() returns an iterator, not a list. To view all elements, you need to consume the iterator (e.g., by converting it to a list or looping through it). Once consumed, the iterator is empty.
  • It stops at the shortest iterable. If you need to handle unequal length iterables differently (e.g., fill missing values), consider itertools.zip_longest.