zip () in Python

Python Methods and Functions

The target of zip () —  display a similar index of multiple containers, so that they can be used simply as a single entity.

Syntax:
zip (* iterators)
Parameters:
Python iterables or containers (list, string etc)
Return Value:
Returns a single iterator object, having mapped values ​​from all the
containers.

# Python code to demonstrate how it works
# zip ()

 
# initializing lists

name = [ "Manjeet" , "Nikhil" , " Shambhavi " , " Astha " ]

roll_no = [ 4 , 1 , 3 , 2 ]

marks = [ 40 , 50 , 60 , 70 ]

 
# using zip () to display values ​​

mapped = zip (name, roll_no, marks)

 
# convert values ​​to print as set

mapped = set (mapped)

 
# print the resulting values ​​

print ( "The zipped result is:" , end = "")

print (mapped)

Output:

 The zipped result is: {('Shambhavi', 3, 60), (' Astha', 2, 70), ('Manjeet', 4, 40), (' Nikhil', 1, 50) } 

How to unpack? Unpacking means converting the archived values ​​back to the individual self. This is done using the " * " operator.

# Python code to demonstrate how it works
# unpack

 
# initialize lists

 

name = [ "Manjeet" , "Nikhil" , "Shambhavi" , "Astha" ]

roll_no = [ 4 , 1 , 3 , 2 ]

marks = [ 40 , 50 , 60 , 70 ]

 
# using zip () to display values

mapped = zip (name, roll_no, marks)

 
# convert values ​​to print as a list

mapped = list (mapped)

 
# print the resulting values ​​

print ( "The zipped result is: " , end = " ")

print (mapped)

 

print ( "" )

 
# unpacking values ​​

namz, roll_noz, marksz = zip ( * mapped)

 

print ( " The unzipped result: " , 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) 

Practical Applications: There are many possible applications that can be said to expect using zip, whether then student database or scorecard or any other utility that requires the display of groups. A small example of a scorecard is shown below.

# Python code to demonstrate usage
# zip ()

 
# initialize the player list.

players = [ "Sachin" , "Sehwag" , "Gambhir" , "Dravid" , "Raina" ]

 
# initialize their score

scores = [ 100 , 15 , 17 , 28 , 43 ]

 
# prints 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 




Tutorials