Python Advanced: What is the Zip method in Python

Home /

Table of Contents

Zip Methods in Python

This chapter of our Python training covers the fantastic and incredibly practical “zip” functionality. Unfortunately, zip frequently causes unnecessary confusion and fear in Python newbies. The name is confusing, to start. Many people mistake the well-known archive file format ZIP, which is used for lossless data compression, for the Python zip. The word “zip” was chosen since this data compression not only maintains the necessary storage space at a very small level but is also completed very quickly. Zip indicates “to act or move fast” in this situation.

We’ll see that understanding zip can be extremely simple. This does not apply, though, if you decide to use the Python help function. This is undoubtedly in part due to the assistance material, which is scary for absolute beginners.

Bring back a zip object whose .next() method produces a tuple with the i-th element coming from the i-th iterable argument. The StopIteration signal is raised when the shortest iterable in the argument sequence has been exhausted by the .next() method.

Although this text is accurate, it is difficult to grasp. Before we attempt to simplify the logic behind the zip, let’s start with some straightforward examples.

Example #1:

fruits = ["apple", "banana", "cherry"]
quantity = [5, 3, 7]
 
zipped_values = zip(fruits, quantity)
 
for t in zipped_values:
   print(t)

Output:

('apple', 5)
('banana', 3)
('cherry', 7)

Example #2:

students = ["Jack Ma", "Elon Musk",
           "Mark Zuckerburg", "Sundar Pichai",
           "Jeff Bezos"]
Title = ['Name:', 'Physics:', 'Mathematics:', 'Chemistry:"']
Physics = [81, 99, 45, 87, 79]
Mathematics = [55, 60, 33, 75, 82]
Chemistry = [71, 65, 89, 99, 35]
 
print(f"{tuple(Title)}")
print('----------------------------------------------')
 
zipped_value = zip(students, Physics, Mathematics, Chemistry)
 
for t in zipped_value:
   print(t)
 

Output:

('Name:', 'Physics:', 'Mathematics:', 'Chemistry:"')
----------------------------------------------
('Jack Ma', 81, 55, 71)
('Elon Musk', 99, 60, 65)
('Mark Zuckerburg', 45, 33, 89)
('Sundar Pichai', 87, 75, 99)
('Jeff Bezos', 79, 82, 35)

Zip can be used for more than just lists and tuples. All iterable objects, including lists, tuples, strings, dictionaries, sets, range, and a variety of others, can be used with it.

Example:

language = ["Python", "Javascript", "Java"]
for item in zip(range(555, 558), language):
   print(item)

Output:

(555, 'Python')
(556, 'Javascript')
(557, 'Java')

Zip with Argument

Let’s examine what occurs when we call zip without any parameters. The loop’s main body was not being performed. What occurs if the zip is called with only one argument, such as a string? As a result, this call generates an iterator that outputs tuples with a single element, in this instance, the characters in the string.

Example:

print('Zip test with or without argument')
 
# Zip without argument
for i in zip():
   print("This will not be printed")
  
string = "Enablegeek"
 
# Zip with argument
for t in zip(string):
   print(t)

Output:

Zip test with or without argument
('E',)
('n',)
('a',)
('b',)
('l',)
('e',)
('g',)
('e',)
('e',)
('k',)

Different Lengths of the Argument

As we’ve seen, an infinite number of iterable objects may be passed as parameters when calling zip. These iterables have previously had the same number of elements or lengths. This is not required. The zip will cease creating an output if the lengths are different as soon as one of the parameter sequences is finished. It will raise a StopIteration exception, just like all other iterators, when it “stops providing an output.” The for loop raises this exception.

Example:

Language = ["Python", "Javascript"]
Framework = ["FastAPI", "ExpressJS", "Spring Boot"]
 
for lang, fram in zip(Language, Framework):
   print(lang, fram)

Output:

Python FastAPI
Javascript ExpressJS

How to Unzip

Unzipping is the process of returning the compressed values to their original state. The “*” operator is used to do this.

Example:

 
Name = ["Jack", "Elon", "Mark", "Sundar", "Jeff"]
 
Roll = [4, 1, 3, 2]
Marks = [40, 50, 60, 70]
 
 
mapped = zip(Name, Roll, Marks)
mapped = list(mapped)
 
print("The zipped result: ")
print(mapped)
print("\n")
 
 
# unzipping values
Name_un, Roll_un, Marks_un = zip(*mapped)
 
print("The unzipped result: \n", end="")
 
print("The Name list is : ", end="")
print(Name_un)
 
print("The Roll list is : ", end="")
print(Roll_un)
 
print("The Marks list is : ", end="")
print(Marks_un)
 

Output:

The zipped result:
[('Jack', 4, 40), ('Elon', 1, 50), ('Mark', 3, 60), ('Sundar', 2, 70)]
 
 
The unzipped result:
The Name list is : ('Jack', 'Elon', 'Mark', 'Sundar')
The Roll list is : (4, 1, 3, 2)
The Marks list is : (40, 50, 60, 70)


Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article