Python zip() function examples

Last updated on March 5, 2021 A Goodman Loading... Post a comment

This article is about the zip() function in Python 3.

Overview

zip() is a built-in function of Python that works like a zipper. It can take zero, one, or many iterables (lists, tuples, dictionaries, etc), aggregates them in a tuple, and return an iterator of tuples with each tuple having elements from all the iterables.

Syntax:

zip(iterables)

To unzip a Python object (for example, a list of tuples), we can also use the zip() function (there is no unzip() function in Python) with the * operator, like this:

zip(*iterables)

Examples

Example 1

The program below will zip the names of the people, emails, and phone numbers respectively.

The code:

names = ['A', 'B', 'C']
emails = ['[email protected]', '[email protected]', '[email protected]']
phone_numbers = [111, 222, 333]

result = zip(names, emails, phone_numbers)
print(list(result))

Output:

[('A', '[email protected]', 111), ('B', '[email protected]', 222), ('C', '[email protected]', 333)]

Example 2

This example using the zip() function to unzip things.

The code:

number_letter_pairs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
numbers, letters = zip(*number_letter_pairs)

print('Numbers', numbers)
print('Letters', letters)

Output:

Numbers (1, 2, 3, 4, 5)
Letters ('a', 'b', 'c', 'd', 'e')

Example 3

This example demonstrates how zip() behaves when the input iterables have different numbers of elements.

The code:

numbers = [1, 2, 3]
letters = ['A', 'B', 'C', 'D']
result = zip(numbers, letters)
print(list(result))

Output:

[(1, 'A'), (2, 'B'), (3, 'C')]

Wrapping Up

This article has covered the basics and walked you through 3 examples of the zip() function. If you want to learn more things in Python, check out the following articles: Python reduce() function examples, Python filter() function examples, Examples of using map() function in Python 3, Examples of numpy.linspace() in Python.

You can also take a glance at our Python topic page for more tutorials and examples.

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x