What are Zip() and Unzip() in Python and how to use the.


Zip() is a built-in (built-in function are the function which are already define in programming framework) function. So basically zip() function takes any number of iterable and returns a list of tuples, the first element of a tuple is created using the first element from each of the iterables, and so on.

Syntax- zip(*iterators)

Practical Application

zip()

We use zip() in various applications related to student databases, matrix problems, etc.

A practical example related to the student database 

name=['aman','naman','akash']      # iterable 1 represent name
roll_no=[23,45,21]                         # iterable 2 represent roll number
marks=[55,67,88]                          # iterable 3 represent marks
result=list(zip(name,roll_no,marks))
print(result)

# Output:  [(‘aman’,23,55),(‘naman’,45,67),(‘akash’,21,88)]

unzip()

just opposite of zip(), means convert the zipped values back to their initial form and this done with the help of the ‘*’ operator.


Example    

name=['aman','naman','akash']
roll_no=[23,45,21]
ziplis=list(zip(name,roll_no))
print(ziplis)
name,roll_no=(zip(*ziplis))
print(name)
print(roll_no)

# Output:  [('aman', 23), ('naman', 45), ('akash', 21)]
              ('aman', 'naman', 'akash')
              (23, 45, 21) 

Zip can also take more than two list and zip them together to get the tupples.

a = [1,2,3,4,5]
b = [2,3,4,5,6]
c = [3,4,5,6,7]
print(zip(a,b,c))
# Output: [(1,2,3),(2,3,4),(3,4,5),(4,5,6),(5,6,7)]

Note: If we apply zip() function on multiple iterators then the iterator with the least items decides the length of the new iterator

This was very basic introduction of these functions, you can read more about them in official documentation.

If you like the article please share and subscribe to keep us motivated.


Gagan Yadav

Travel and Management Student who is very interested in Coding and Python. Certified Mountaineer and baller

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Are you preparing for DevOps and SRE Interview?

Here is a book for you.


Interview preparation and interview questions for DevOps and SRE






A good reads for last-minute preparations for handling DevOps and SRE interviews at companies like LinkedIn, Visa, Atlassian, etc.