Python Zip | Zip Function in Python Explained with Examples

[ad_1]

This tutorial covers the following topic – Python Zip. It describes the syntax of the zip() function in Python. Also, it explains how the zip works and how to use it with the help of examples.

The zip() function allows a variable number of arguments (0 or more), but all iterables. The data types like Python list, string, tuple, dictionary, set, etc. are all of the iterable types.

It groups the corresponding elements of all input iterables to form tuples, consolidates, and returns as a single iterable. Let’s check out about the Python zip function in more detail.

Zip() Function Explained with Examples

What is zip in Python?

The zip() is a built-in Python function. It is used to create an iterator of tuples (known as zip object) from a list of iterables passed as arguments.

Each tuple in the iterator contains elements that exist at a similar index in all the input iterables.

The size of the zip object depends on the shortest of the iterables passed to the Python zip function.

Python zip() syntax

''' Syntax(1) '''
 zip(iterator_1, iterator_2, iterator_3 ...)

Alternatively, the following syntax can also be referred:

''' Syntax(2) '''
 zip(*iterables)

Zip() parameters

The zip() function allows:

Python iterables or collections such as a list, string, dictionary, set, or any custom iterables.

Zip() return value

The zip() function returns a consolidated iterator that contains tuples holding adjacent values from input containers.

READ – Python Iterator

  • In case of zero no. of arguments, zip() returns a zero-sized iterator.
  • When only one iterable is passed, zip() still returns an iterator holding tuples with a single cardinal value. It means that every tuple will have one element.
  • In the case of multiple iterable arguments, the values at a similar index are grouped to form a tuple, and this process continues N times. N is the length of the shortest of iterables in the zip() parameters.

Simple zip() function example

# Python zip function simple example

# Setting up lists 
prog_langs = ["python", "java", "c", "javascript"] 
tiobe_ranks = [1, 2, 3, 4]
features = [10, 20, 30, 40]

# Display input lists
print ("nTest Input: **********n Prog Langs : " + str(prog_langs)) 
print (" TIOBE Ranks : " + str(tiobe_ranks)) 
print (" Features : " + str(features)) 

# Using zip() to group values
zip_obj = zip(prog_langs, tiobe_ranks, features)

# printing zip object
print ("nTest Result: **********n Type of zip_obj is : ", type(zip_obj))

# convert zip object to a set 
final_res = set(zip_obj) 

# printing python zip result
print (" The final result after zip() : n", final_res)

You may check from the result that zip function generates a Python zip object. The above sample used Python type() to confirm the same.

Let’s now summarize the execution output:

Python zip function simple example

Python zip example with iterables of varied sizes

Let’s now try to zip multiple lists (more than two), and see how the zip function pairs their elements together.

In the below example, we’ve used three lists for the demo with their respective sizes 5, 6, and 4. Therefore, the third list, which has four elements, is the smallest. And it is the one to decide the length of the result of the Python zip() function.

# Python zip function
# Zip two or more lists of different sizes

# Setting up lists 
in_list1 = [11, 21, 34, 12, 31] 
in_list2 = [23, 25, 54, 24, 20, 27] 
in_list3 = [23, 25, 54, 24] 

# Display input lists 
print ("nTest Input: **********n Input List (1) : " + str(in_list1)) 
print (" Input List (2) : " + str(in_list2)) 
print (" Input List (3) : " + str(in_list3)) 

# Find the smallest list to iterate
size_smallest_list = min(len(in_list1), len(in_list2), len(in_list3))

# Call the zip function on input lists of different sizes
out = zip(in_list1, in_list2, in_list3)

# Convert zip object to a list
result_set = list(out)

# printing zip() result
print ("nTest Result: **********n Size of the smallest list is : ", size_smallest_list) 
print (" Size of the zipped resultant list is : ", len(result_set))
print (" Zipped resultant list is : n", result_set)

This example will give the following outcome:

Zip two or more lists of different sizes in Python

Zip and unzip values

You can also unzip the Python zip object or extract the output of the zip() function. And interestingly, you’ll be doing it through the zip() function only. The difference is an asterisk sign that you will need to prepend to the zip argument.

Given below is an example to help you understand it better.

# Python zip function with asterisk (*) in argument
# Unzip the Python zip object

# Setting up lists 
list_of_countries = ["USA", "UK", "GERMANY", "FRANCE", "INDIA"] 
list_of_capitals = ["New York", "London", "Berlin", "Paris", "Delhi"] 

# Display input lists 
print ("nTest Input: **********n Input List (1) : " + str(list_of_countries)) 
print (" Input List (2) : " + str(list_of_capitals)) 

# Call the zip function on test input lists
zip_result = zip(list_of_countries, list_of_capitals)

# Convert zip result to a list
zipped_list = list(zip_result)

# Now, unzip the zipped result
countries, capitals = zip(*zipped_list)

# printing unzip result
print ("nTest Result: **********") 
print (" Unzipped list of countries : ", countries)
print (" Unzipped list of capitals : ", capitals)

This program will produce the following result:

Unzip the Python zip object

Zip and for loop to iterate over two lists in parallel

Using Python zip, you can even iterate multiple lists in parallel in a For loop. It is possible because the zip function returns a list of tuples, where the ith tuple gets elements from the ith index of every zip argument (iterables).

Check out the example below:

# Zip to iterate over multiple lists in parallel

# Setting up test lists 
prog_langs = ["Python", "Java", "C", "JavaScript"] 
tiobe_ranks = [1, 2, 3, 4]
features = [10, 20, 30, 40]

print ("nTest Input: **********n  PROG LANGS : " + str(prog_langs)) 
print (" TIOBE RANKS : " + str(tiobe_ranks)) 
print ("    FEATURES : " + str(features))


# Iterate lists in parallel using for loop
print("nTest Output: **********")
for lang, rank, feat in zip(prog_langs, tiobe_ranks, features):
  print(" {0:10}, {0:10}, {0:10}".format(lang, rank, feat))

The below image captures the result of the above example:

iterate over multiple lists in parallel

Please note that we’ve used Python format function here for string padding. You must refer to the linked tutorial if you are interested to take formatting a step further.

Python zip to sort lists in parallel

It’s sometimes a goal for the programmers to sort a list as fast as possible. And what could be more challenging than sorting multiple lists together?

So, let’s assume, you have to join two lists and sort them in parallel. In the below example, we’ll use the sorted() function along with the zip() function. Or you can even see to call the Python list sort to do this.

# Python zip to sort lists in parallel

# Setting up lists 
list_of_countries = ["USA", "UK", "GERMANY", "FRANCE", "INDIA"] 
list_of_capitals = ["New York", "London", "Berlin", "Paris", "Delhi"] 

# Display input lists 
print ("nTest Input: **********n Input List (1) : " + str(list_of_countries)) 
print (" Input List (2) : " + str(list_of_capitals)) 

# Sort by countires using zip() and sorted() functions
sorted_by_countries = sorted(list(zip(list_of_countries, list_of_capitals)))

# Sort by capitals using zip() and sorted() functions
sorted_by_capitals = sorted(list(zip(list_of_capitals, list_of_countries)))

# printing unzip result
print ("nTest Result: **********") 
print (" Sorted list by countries : n", sorted_by_countries)
print ("n Sorted list by capitals : n", sorted_by_capitals)

You can find the result of the above example in the below screenshot:

sort lists in parallel

Compare zip(): Python 2 vs. 3

The zip() function has got a slight change in the behavior in Python 3.

In Python 2, it used to return a list of tuples of the size equal to the shortest of the input iterables. Also, an empty zip() call would get you an empty list.

Whereas in Python 3, the zip() is reimplemented to return an iterator. Upon traversing, it gets you the tuple from the zipped result one by one. Remember, you can iterate over it only once. With empty arguments, it returns a zero-sized iterator.

You have now reached the end of this tutorial. And we hope that you’ve got to learn a lot about the Python zip() function and some of its most essential features. By the way, to learn Python from scratch to depth, do read our step by step Python tutorial.

[ad_2]

Leave a Comment