zip()

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:

Code
Output
Loading...

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:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Python on Codecademy

Contributors