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:
- Anonymous contributorAnonymous contributor3077 total contributions
- CyberRedPanda27 total contributions