Note
Python - zip() - Combine elements from multiple iterables
Overview of the Python zip() function. Combine elements from several iterables.
zip(iterable_1, iterable_2, ...) returns lazy iterator that contains tuples with combined elements one by one from each iterable.
Each tuple contains elements from the corresponding position in each iterable.
Thezip() function is often used to combine data from multiple lists, tuples, or other iterables, making it a powerful tool for data processing and iteration in Python.
Python zip() function stops creating tuples when the shortest iterable is exhausted which is useful for handling uneven iterables.
my_list_1 = [1, 2, 3, 4, 5]
my_string_1 = "devcuriosity"
my_zip = zip(my_list_1, my_string_1)
for element in my_zip:
print(element)
Output:
(1, 'd')
(2, 'e')
(3, 'v')
(4, 'c')
(5, 'u')
Please notice that order of iterables is preserved.
Using zip() with multiple iterables
zip() can also accept more arguments:
my_list_1 = [1, 2, 3, 4, 5]
my_string_1 = "devcuriosity"
my_range = range(0, 3)
another_zip = zip(my_list_1, my_string_1, my_range)
for element in another_zip:
print(element)
Output:
(1, 'd', 0)
(2, 'e', 1)
(3, 'v', 2)
Please notice that zip() stops when the shortest iterable is exhausted.
Alternative for uneven iterables - zip_longest()
If you want to zip multiple iterables and continue until the longest iterable is exhausted, consider using itertools.zip_longest().
It will fill in missing values from shorter iterables with a specified (and optional) fillvalue.
Key Points to Remember about zip()
-
Lazy Evaluation:
zip()returns an iterator, generating tuples only when needed, which is memory-efficient. -
Uneven Iterables:
zip()stops when the shortest iterable is exhausted, so it does not raise errors with uneven iterables. -
Order Preservation: The order of elements in each tuple matches the order of the iterables passed to
zip().
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!