Home Python Tutorial What is zip() in Python

What is zip() in Python

by Anup Maurya
21 minutes read

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:

  1. We have two lists: fruits and colors.
  2. The zip() function is called with these lists as arguments.
  3. It creates an iterator of tuples, where each tuple contains an element from fruits and an element from colors at the same position.
  4. 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 the zip() 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.

Leave a Comment

Enable Notifications OK No thanks