Takes multiple iterators as input and returns a single zip object made up of a list of tuples.
zip(iterator1, iterator2, ...)
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)]
zip() returns an iterator, it is necessary to use the
list() function, or a similar function like
set(), to work with the result:
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')]
5 are not included.
You can also unzip a zip object:
Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.
Learn Python on Codecademy
Analyze Data with PythonLearn to analyze and visualize data using Python and statistics.
Includes 8 Courses