The Wayback Machine - https://web.archive.org/web/20240717152401/https://www.geeksforgeeks.org/zip-in-python/
Open In App

zip() in Python

Last Updated : 07 Nov, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
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




Similar Reads

Zip function in Python to change to a new character set
Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcdâ€Ķ.xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output : co
2 min read
Application to get address details from zip code Using Python
Prerequisite: Tkinter In this article, we are going to write scripts to get address details from a given Zip code or Pincode using tkinter and geopy module in python, Tkinter is the most commonly used GUI module in python to illustrate graphical objects and geopy is a python module to locate the coordinates of addresses, cities, countries, landmark
2 min read
Get Zip Code with given location using GeoPy in Python
In this article, we are going to write a python script to get the Zip code by using location using the Geopy module.geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the world. To install the Geopy module, run the following command in your terminal. pip install geopy Approach:
2 min read
Python program for Zip, Zap and Zoom game
Zip zap zoom is a fun game that requires its players to concentrate and participate actively. When this game is played with people, this is how it is played: Players stand in a circle, 6 feet away from each otherOne player starts the game by clap-pointing and saying zap to the person on its leftThis person now does the same to the person to its rig
3 min read
Create Password Protected Zip of a file using Python
ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep re
2 min read
How to Brute Force ZIP File Passwords in Python?
In this article, we will see a Python program that will crack the zip file's password using the brute force method. The ZIP file format is a common archive and compression standard. It is used to compress files. Sometimes, compressed files are confidential and the owner doesn't want to give its access to every individual. Hence, the zip file is pro
3 min read
Working with zip files in Python
This article explains how one can perform various operations on a zip file using a simple python program. What is a zip file? ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZI
5 min read
Use enumerate() and zip() together in Python
In this article, we will discuss how to use enumerate() and zip() functions in python. Python enumerate() is used to convert into a list of tuples using the list() method. Syntax: enumerate(iterable, start=0) Parameters: Iterable: any object that supports iterationStart: the index value from which the counter is to be started, by default it is 0Pyt
4 min read
Create pandas dataframe from lists using zip
One of the way to create Pandas DataFrame is by using zip() function. You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe. zip() function creates the objects and that can be used to produce single item at a time. This function can create pandas DataFrames by mer
2 min read
PYGLET – Creating ZIP Location Object
In this article we will see how we can create a ZIP location object in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an
3 min read
three90RightbarBannerImg