This python tutorial helps to understand Python’s zip()
function with examples. The zip() is a built-in Python function that accepts any type of iterable and returns us an iterator of tuples. This method creates an iterator that will aggregate elements from two or more iterables.
This built-in function creates an iterator that aggregates elements from two or more iterables into tuples.
The Syntax of Python Zip :
zip(iterator1, iterator2, iterator3 …)
If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
Zip iterators With the Equal Length
We will pass tuples with the same length into the zip() method.
tuple_items = ("Red", "Green", "Yellow") tuple_items1 = ("Danger", "Success", "Warning") combined_list = zip(tuple_items, tuple_items1) print(combined_list)
Output:
$python main.py [('Red', 'Danger'), ('Green', 'Success'), ('Yellow', 'Warning')]
Zip iterators With Unequal Length
Now, let’s pass tuples with different lengths into the zip()
method.
tuple_items = ("Red", "Green", "Yellow") tuple_items1 = ("Danger", "Success", "Warning", "Process") combined_list = zip(tuple_items, tuple_items1) print(combined_list)
Output:
$python main.py [('Red', 'Danger'), ('Green', 'Success'), ('Yellow', 'Warning')]
Handling No Arguments in Python zip()
You can call zip()
with no arguments as well, resulting in an empty iterator.
map_list = zip() print(list(map_list))
You’ll simply get an empty iterator. The map_list
variable holds an empty iterator.
Output:
$python main.py []
Handling One Argument in Python zip()
You can call zip()
with one argument as well.
tuple_items = ("Red", "Green", "Yellow") map_list = zip(tuple_items) print(list(map_list))
You’ll simply get a series of 1-item tuples. The length of the resulting tuples will always equal the number of iterables you pass as arguments.
Output:
$python main.py [('Red',), ('Green',), ('Yellow',)]
Traversing Lists in Parallel Using Zip
Python’s zip()
the function allows you to iterate in parallel over two or more iterables. You can traverse tuples using a for loop:
l1_items = ["Red", "Green", "Yellow"] l2_items1 = ["Danger", "Success", "Warning"] for i, j in zip(l1_items, l2_items1): print(i, j)
Output:
$python main.py ('Red', 'Danger') ('Green', 'Success') ('Yellow', 'Warning')
Using zip()
allows for efficient and concise parallel traversal of iterables, making it a valuable tool in Python programming.
Conclusions
Data aggregation and parallel traversal are two examples of the operations that are made possible by the zip() method, which generates an iterator that combines elements into tuples. Either equal or unequal length iterables can be used; zip() effectively manages the data and makes sure the output iterator matches the shortest input iterable.