The Wayback Machine - https://web.archive.org/web/20230620125637/https://www.geeksforgeeks.org/zip-in-python/
Skip to content
Related Articles
Open In App

Related Articles

zip() in Python

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

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.

Python zip() 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:

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

Python zip() with enumerate

The zip() function in Python is commonly used to combine two or more iterables, such as lists, tuples, or strings, into a single iterable where elements from corresponding positions are paired together. On the other hand, the enumerate() function is used to iterate over an iterable and return both the index and the corresponding element at that index. It is often used in for loops to keep track of the index of the current iteration. When zip() and enumerate() are used together, it allows for iterating over multiple iterables while also keeping track of their indices. 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')]

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




# Python code to demonstrate the working of
# unzip
 
# 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)

Explanation :

3 Lists name, roll_no, and marks are initialized with values. The zip() function is used to map the values from these lists together into tuples, and the result is stored in the mapped variable. The zip() function combines the elements of multiple iterables (in this case, 3 lists) into tuples, where the i-th tuple contains the i-th elements from each of the input iterables. The mapped variable will contain tuples with three elements each, representing the values from name, roll_no, and marks lists combined together. The mapped variable is converted into a list using the list() function and printed, showing the zipped result of 3 lists. The output will be a list of tuples, where each tuple contains the values from name, roll_no, and marks lists combined together. Next, the zip() function is used again with the * (splat) operator to unzip the mapped variable. The * operator is used to unpack the tuples in mapped, so that each tuple is passed as separate positional arguments to the zip() function. This effectively transposes the tuples, separating the values from name, roll_no, and marks into three separate tuples. The resulting tuples after unzipping are assigned to three separate variables namz, roll_noz, and marksz, respectively. Finally, the original lists namz, roll_noz, and marksz are printed using separate print statements.

Practical Applications

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

Explanation :

Two lists, players and scores, are initialized with values representing the names of players and their respective scores.A for loop is used to iterate over the players and scores lists simultaneously using the zip() function. The zip() function pairs the corresponding elements of the two lists together. Inside the loop, the values of players and scores for the current iteration are retrieved and assigned to the variables pl and sc, respectively.The print() function is used to display the names of the players and their scores using string formatting, with %s representing the player’s name and %d representing the score as an integer.The loop continues for each pair of elements in the players and scores lists, printing the player’s name and their score in the specified format.


Last Updated : 18 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials