Open In App

zip() in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Python zip() method takes iterable containers and returns a single iterator object, having mapped values from all the containers. 

Python zip() Syntax

It is used to map the similar index of multiple containers so that they can be used just using a single entity. 

Syntax :  zip(*iterators) 

Parameters : Python iterables or containers ( list, string etc ) 
Return Value : Returns a single iterator object.

zip() in Python Examples

Python zip() with lists

In Python, the zip() function is used to combine two or more lists (or any other iterables) into a single iterable, where elements from corresponding positions are paired together. The resulting iterable contains tuples, where the first element from each list is paired together, the second element from each list is paired together, and so on.

Python3




name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]
roll_no = [ 4, 1, 3, 2 ]
 
# using zip() to map values
mapped = zip(name, roll_no)
 
print(set(mapped))


Output

{('Nikhil', 1), ('Shambhavi', 3), ('Manjeet', 4), ('Astha', 2)}


Python zip() with enumerate

The combination of zip() and enumerate() is useful in scenarios where you want to process multiple lists or tuples in parallel, and also need to access their indices for any specific purpose.

Python3




names = ['Mukesh', 'Roni', 'Chari']
ages = [24, 50, 18]
 
for i, (name, age) in enumerate(zip(names, ages)):
    print(i, name, age)


Output

0 Mukesh 24
1 Roni 50
2 Chari 18


Python zip() with Dictionary

The zip() function in Python is used to combine two or more iterable dictionaries into a single iterable, where corresponding elements from the input iterable are paired together as tuples. When using zip() with dictionaries, it pairs the keys and values of the dictionaries based on their position in the dictionary.

Python3




stocks = ['GEEKS', 'For', 'geeks']
prices = [2175, 1127, 2750]
 
new_dict = {stocks: prices for stocks,
            prices in zip(stocks, prices)}
print(new_dict)


Output

{'GEEKS': 2175, 'For': 1127, 'geeks': 2750}


Python zip() with Tuple

When used with tuples, zip() works by pairing the elements from tuples based on their positions. The resulting iterable contains tuples where the i-th tuple contains the i-th element from each input tuple.

Python3




tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
zipped = zip(tuple1, tuple2)
result = list(zipped)
print(result)


Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

Python zip() with Multiple Iterables

Python’s zip() function can also be used to combine more than two iterables. It can take multiple iterables as input and return an iterable of tuples, where each tuple contains elements from the corresponding positions of the input iterables.

Python3




list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['x', 'y', 'z']
zipped = zip(list1, list2, list3)
result = list(zipped)
print(result)


Output

[(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]


Zipping lists of unequal size

The zip() function will only iterate over the smallest list passed. If given lists of different lengths, the resulting combination will only be as long as the smallest list passed. In the following code example:

Python3




# Define lists for 'persons', 'genders', and a tuple for 'ages'
persons = ["Chandler", "Monica", "Ross", "Rachel", "Joey", "Phoebe", "Joanna"]
genders = ["Male", "Female", "Male", "Female", "Male", "Female", "Female"]
ages = (35, 36, 38, 34)
 
# Create a zipped object combining the 'persons' and 'genders'
#lists along with the 'ages' tuple
zipped_result = zip(persons, genders, ages)
 
# Print the zipped object
print("Zipped result as a list:")
for i in list(zipped_result):
  print(i)


Output

Zipped result as a list:
('Chandler', 'Male', 35)
('Monica', 'Female', 36)
('Ross', 'Male', 38)
('Rachel', 'Female', 34)


Unzipping Using zip()

Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator.

Python3




# initializing lists
name = ["Manjeet", "Nikhil", "Shambhavi", "Astha"]
roll_no = [4, 1, 3, 2]
marks = [40, 50, 60, 70]
 
# using zip() to map values
mapped = zip(name, roll_no, marks)
 
# converting values to print as list
mapped = list(mapped)
 
# printing resultant values
print("The zipped result is : ", end="")
print(mapped)
 
print("\n")
 
# unzipping values
namz, roll_noz, marksz = zip(*mapped)
 
print("The unzipped result: \n", end="")
 
# printing initial lists
print("The name list is : ", end="")
print(namz)
 
print("The roll_no list is : ", end="")
print(roll_noz)
 
print("The marks list is : ", end="")
print(marksz)


Output

The zipped result is : [('Manjeet', 4, 40), ('Nikhil', 1, 50), 
('Shambhavi', 3, 60), ('Astha', 2, 70)]
The unzipped result: 
The name list is : ('Manjeet', 'Nikhil', 'Shambhavi', 'Astha')
The roll_no list is : (4, 1, 3, 2)
The marks list is : (40, 50, 60, 70)

Using zip() with Python Loops

There are many possible applications that can be said to be executed using zip, be it student database or scorecard or any other utility that requires mapping of groups. A small example of a scorecard is demonstrated below. 

Python3




# Python code to demonstrate the application of
# zip()
 
# initializing list of players.
players = ["Sachin", "Sehwag", "Gambhir", "Dravid", "Raina"]
 
# initializing their scores
scores = [100, 15, 17, 28, 43]
 
# printing players and scores.
for pl, sc in zip(players, scores):
    print("Player :  %s     Score : %d" % (pl, sc))


Output

Player :  Sachin     Score : 100
Player :  Sehwag     Score : 15
Player :  Gambhir     Score : 17
Player :  Dravid     Score : 28
Player :  Raina     Score : 43




Last Updated : 07 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads