The zip() is a built-in Python function that creates an iterator that will aggregate elements from two or more iterables. The function takes the iterable elements like input and returns the zip object, an iterator of tuples where the first item in each passed iterator is paired. The iterator stops when the shortest input iterable is exhausted.
Syntax
zip(iterable1, iterable2, ...)
Arguments
iterable1, iterable2, …: Two or more input iterables to be combined using zip().
Example 1
# Define sample iterables
names = ["KRUNAL", "ANKIT", "RUSHABH"]
ages = [30, 25, 35]
# Use zip() to combine the iterables
zipped = zip(names, ages)
# Convert the zipped object to a list and print it
zipped_list = list(zipped)
print("Zipped list:", zipped_list)
Output
Zipped list: [('KRUNAL', 30), ('ANKIT', 25), ('RUSHABH', 35)]
In this code example, we have two lists of names and ages.
In the next step, we used the zip() function to combine these lists into a single list of tuples, where each tuple contains a name and its corresponding age.
Example 2
You can also use the zip() function in a for loop.
# Define sample iterables
names = ["KRUNAL", "ANKIT", "RUSHABH"]
ages = [30, 25, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Output
KRUNAL is 30 years old
ANKIT is 25 years old
RUSHABH is 35 years old
In this code example, we used the zip() function to create an iterator of tuples, and we directly iterated over the tuples in a for loop to print the name and age of each person.
Example 3
To “unzip” the values combined using the “zip()” function, you can use the “zip() function again with the * operator” (unpacking operator) to unpack the zipped values back into their original form.
# Define sample iterables
names = ["KRUNAL", "ANKIT", "RUSHABH"]
ages = [30, 25, 35]
zipped = zip(names, ages)
# Unzip the zipped values using zip() and the unpacking operator
unzipped_names, unzipped_ages = zip(*zipped)
# Convert the unzipped values to lists and print them
unzipped_names_list = list(unzipped_names)
unzipped_ages_list = list(unzipped_ages)
print("Unzipped names:", unzipped_names_list)
print("Unzipped ages:", unzipped_ages_list)
Output
Unzipped names: ['KRUNAL', 'ANKIT', 'RUSHABH']
Unzipped ages: [30, 25, 35]
In this code example, we combined the names and ages lists using the zip() function.
In the next step, we used the zip() function again with the unpacking operator (*) to “unzip” the combined values back into separate iterables.
We converted the unzipped values to lists and printed them, showing that the original names and ages lists were successfully reconstructed.
That’s it.