zip()
Published Jun 14, 2021Updated Sep 3, 2021
Contribute to Docs
Takes multiple iterators as input and returns a single zip object made up of a list of tuples.
Syntax
zip(iterator1, iterator2, ...)
Example 1
zip()
can be used to combine iterators such as lists. Objects will be combined from left to right.
my_pets = ['cat', 'dog', 'bird', 'great white shark']my_pets_weight_in_pounds = [9, 50, 0.33, 2000]combined = zip(my_pets, my_pets_weight_in_pounds)print(list(combined))# Output: [('cat', 9), ('dog', 50), ('bird', 0.33), ('great white shark', 2000)]
Example 2
Because zip()
returns an iterator, it is necessary to use the list()
function, or a similar function like tuple()
or set()
, to work with the result:
Example 3
If one of the iterators passed in as a parameter to zip()
contains more objects than another, then the extra objects will be ignored:
numbers = [1, 2, 3, 4, 5]letters = ['a', 'b', 'c']combined = zip(numbers, letters)print(list(combined))# Output: [(1, 'a'), (2, 'b'), (3, 'c')]
Notice how 4
and 5
are not included.
Example 4
You can also unzip a zip object:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Skill path
Analyze Data with Python
Learn to analyze and visualize data using Python and statistics.Includes 8 CoursesWith CertificateIntermediate13 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours