Python Tutorial Python Advanced Python References Python Libraries

Python zip() Function



The Python zip() function returns a zip object which contains mapped values from similar indexes of multiple iterators. The values in the zipped object are mapped as tuples.

Syntax

zip(iterator1, iterator2, ...)

Parameters

iterator1, iterator2, ... Required. iterator objects which need to be mapped

Example:

In the example below, three iterators called month, min_temp and max_temp are mapped using zip() function.

month = ['JAN', 'FEB', 'MAR', 'APR']
min_temp = [-10, -5, -2, -1]
max_temp = [1, 5, 10, 15]

x = zip(month, min_temp, max_temp)
y = list(x)

#Accessing elements from zipped object
print(y[0])
print(y[1])
print(y[2])

The output of the above code will be:

('JAN', -10, 1)
('FEB', -5, 5)
('MAR', -2, 10)

Unzip the zipped object

To unzip a zipped object, the "*" operator is used. Using this operator, every mapped values can be stripped into tuples.

Example:

In the example below, the zipped object y is unzipped using "*" operator.

month = ['JAN', 'FEB', 'MAR', 'APR']
min_temp = [-10, -5, -2, -1]
max_temp = [1, 5, 10, 15]

x = zip(month, min_temp, max_temp)
y = list(x)

month_unzipped , min_temp_unzipped, max_temp_unzipped = zip(*y)

print(month_unzipped)
print(min_temp_unzipped)
print(max_temp_unzipped)

The output of the above code will be:

('JAN', 'FEB', 'MAR', 'APR')
(-10, -5, -2, -1)
(1, 5, 10, 15)

❮ Python Built-in Functions