Articles

Python Zip Function: Complete Guide with Examples

Learn the `zip()` function in Python with syntax, examples, and best practices. Master parallel iteration and list combining efficiently.

What is the zip() function in Python?

The zip() function is a built-in Python utility used to combine multiple iterable objects (such as lists, tuples, or strings) into a single iterable of tuples. Each tuple contains elements from the corresponding position of the input iterables. This function is commonly used when we want to pair or group elements together from multiple sequences in a structured way.

Imagine we have two lists—one with names and one with scores. If we want to match each name with the corresponding score, zip() makes that task effortless by zipping the lists together like the two sides of a zipper.

Key characteristics

The key characteristics of the Python zip() function include:

  • Element-wise pairing: zip() matches elements based on their index.
  • Returns a zip object: zip() doesn’t return a list directly. Instead, it returns a special iterator that can be converted into a list or tuple if needed.
  • Stops at the shortest input: If the input iterables have different lengths, zip() stops creating pairs when the shortest iterable is exhausted, which prevents IndexError.

Next, let’s check out the syntax for the zip() function in Python.

Related Course

Learn Python 3

Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today. Try it for free

Python zip() function syntax

Here is the syntax for the Python zip() function:

zip(iterable1, iterable2, ...) 

Parameters:

  • iterable1, iterable2, ...: One or more iterable objects (e.g., lists, tuples, strings).

Return value:

Returns a zip object, which is an iterator of tuples.

To view the output, we typically convert it to a list or a tuple:

print(list(zip(['a', 'b'], [1, 2]))) # Output: [('a', 1), ('b', 2)]

Now that we’re familiar with the syntax, let’s see an example that demonstrates the usage of the zip() function in Python.

Python zip() function example

Here is an example for the Python zip() function:

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 88]
zipped = zip(names, scores)
print(list(zipped))

In this example, each element from the names list is paired with the corresponding element from the scores list to form a tuple. These tuples are collected in a single iterable structure, making further processing or iteration much easier.

Here is the output:

[('Alice', 85), ('Bob', 90), ('Charlie', 88)]

Now that we know how zip() works, let’s explore some common use cases for this function.

Python zip() function use cases

Let’s go through some common use cases for the zip() function in Python.

1. Combine two Lists into tuples

This example uses zip() to combine two lists into tuples:

list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
combined = list(zip(list1, list2))
print(combined)

Here is the output:

[('a', 1), ('b', 2), ('c', 3)]

2. Create a dictionary from two lists

This example uses zip() to create a dictionary from two lists:

keys = ['id', 'name', 'age']
values = [101, 'Alice', 25]
dictionary = dict(zip(keys, values))
print(dictionary)

Here is the output:

{'id': 101, 'name': 'Alice', 'age': 25}

3. Unzip a zipped object

This example uses zip() with the * operator to unzip a zipped object:

zipped = [('a', 1), ('b', 2)]
letters, numbers = zip(*zipped)
print(letters)
print(numbers)

Here is the output:

('a', 'b')
(1, 2)

With the use cases covered, let’s check out the differences between zip() and other Python functions.

Zip vs other Python functions

Here is a table that compares zip() with other Python functions:

Feature zip() enumerate() itertools.zip_longest()
Purpose Combine iterables Add index to iterable Combine with padding
Stops at Shortest sequence Single iterable Longest sequence
Returns Tuples of elements Index-value pairs Padded tuples

Lastly, let’s discover some best practices for using the Python zip() function.

Python Zip Function Best Practices

Apply these best practices to make the most out of the zip() function in Python:

  • Prefer zip() over manual indexing: Avoid using range(len(...)) when iterating over multiple sequences—zip() is more readable and Pythonic.
  • Convert the zip object when needed: Since zip() returns an iterator, convert it into a list or tuple (e.g., list(zip(...))) if you need to access the data multiple times.
  • Use descriptive variable names: When unpacking zipped items in loops, choose meaningful variable names to make the code clearer and easier to understand.
  • Handle uneven iterable lengths cautiously: zip() stops at the shortest iterable. Use itertools.zip_longest() if you need to preserve all elements and handle padding.

These best practices will ensure effective usage of the Python zip() function.

Conclusion

In this article, we discussed what the zip() function is in Python and how it works. We explored the syntax and practical examples to get a better understanding of the function. Moreover, we discovered some common use cases and best practices that will allow us to use zip() efficiently.

The Python zip() function is a small but mighty tool that simplifies working with multiple sequences. Whether we’re combining lists, creating dictionaries, or iterating over multiple datasets, zip() provides a clean, Pythonic solution.

If you want to expand your knowledge of Python, check out the Learn Python 3 course on Codecademy.

Frequently asked questions

1. What does zip() return in Python?

zip() returns a zip object (an iterator of tuples).

2. Can you zip() more than two lists?

Yes, you can pass any number of iterables to zip().

3. What happens if the iterables passed to zip() have different lengths?

zip() stops at the shortest iterable.

4. How do you unzip a zipped object using zip()?

Use the * operator with zip():

zip(*zipped_object)

5. What is the difference between zip() and itertools.zip_longest()?

While zip() stops combining at the shortest iterable, itertools.zip_longest() continues until the longest iterable is reached, filling missing values with a specified default (e.g., None).

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team