The zip() function is used to pair elements from multiple iterables sequentially into tuples, returning an iterable zip object.
Function Syntax
zip(*iterables)
Here, *iterables represents multiple iterable objects, such as lists, tuples, sets, etc.
Examples of the zip() Function
Combining multiple lists into a list of tuples:
list1 = ['x', 'y', 'z']
list2 = [1, 2, 3]
list3 = ['a','b','c']
print(list(zip(list1)))
print(list(zip(list1,list2)))
print(list(zip(list1,list2,list3)))
[('x',), ('y',), ('z',)]
[('x', 1), ('y', 2), ('z', 3)]
[('x', 1, 'a'), ('y', 2, 'b'), ('z', 3, 'c')]
Iterating over a zip object:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
# The returned zip object is an iterator
for char, number in zip(list1, list2):
print(char,number)
# Output
# a 1
# b 2
# c 3
Using the * operator to unzip a list of tuples:
pairs = [('a', 1), ('b', 2), ('c', 3)]
chars, numbers = zip(*pairs)
print(chars) # ('a', 'b', 'c')
print(numbers) # (1, 2, 3)