What is zip () in python?

❮ Built-in Functions


Example

Join two tuples together:

a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica")

x = zip(a, b)

Try it Yourself »


Definition and Usage

The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.


Syntax

zip(iterator1, iterator2, iterator3 ...)

Parameter Values

ParameterDescription
iterator1, iterator2, iterator3 ... Iterator objects that will be joined together

More Examples

Example

If one tuple contains more items, these items are ignored:

a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica", "Vicky")

x = zip(a, b)

Try it Yourself »

❮ Built-in Functions


The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

Example

languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]

result = zip(languages, versions)

print(list(result)) # Output: [('Java', 14), ('Python', 3), ('JavaScript', 6)]


Syntax of zip()

The syntax of the zip() function is:

zip(*iterables)

zip() Parameters

ParameterDescription
iterables can be built-in iterables (like: list, string, dict), or user-defined iterables

Recommended Reading: Python Iterators, __iter__ and __next__


zip() Return Value

The zip() function returns an iterator of tuples based on the iterable objects.

  • If we do not pass any parameter, zip() returns an empty iterator
  • If a single iterable is passed, zip() returns an iterator of tuples with each tuple having only one element.
  • If multiple iterables are passed, zip() returns an iterator of tuples with each tuple having elements from all the iterables.

    Suppose, two iterables are passed to zip(); one iterable containing three and other containing five elements. Then, the returned iterator will contain three tuples. It's because the iterator stops when the shortest iterable is exhausted.


Example 1: Python zip()

number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']

# No iterables are passed

result = zip()

# Converting iterator to list result_list = list(result) print(result_list) # Two iterables are passed

result = zip(number_list, str_list)

# Converting iterator to set result_set = set(result) print(result_set)

Output

[]
{(2, 'two'), (3, 'three'), (1, 'one')}

Example 2: Different number of iterable elements

numbersList = [1, 2, 3]
str_list = ['one', 'two']
numbers_tuple = ('ONE', 'TWO', 'THREE', 'FOUR')

# Notice, the size of numbersList and numbers_tuple is different

result = zip(numbersList, numbers_tuple)

# Converting to set result_set = set(result) print(result_set)

result = zip(numbersList, str_list, numbers_tuple)

# Converting to set result_set = set(result) print(result_set)

Output

{(2, 'TWO'), (3, 'THREE'), (1, 'ONE')}
{(2, 'two', 'TWO'), (1, 'one', 'ONE')}

The * operator can be used in conjunction with zip() to unzip the list.

zip(*zippedList)

Example 3: Unzipping the Value Using zip()

coordinate = ['x', 'y', 'z']
value = [3, 4, 5]

result = zip(coordinate, value)
result_list = list(result)
print(result_list)

c, v = zip(*result_list)

print('c =', c) print('v =', v)

Output

[('x', 3), ('y', 4), ('z', 5)]
c = ('x', 'y', 'z')
v = (3, 4, 5)

Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. 

It is used tomap 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, having mapped values from all the 
containers.

Python zip() example

Example 1: Python zip two lists

Python3

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

roll_no = [ 4, 1, 3, 2 ]

mapped = zip(name, roll_no)

print(set(mapped))

Output:

{('Shambhavi', 3), ('Nikhil', 1), ('Astha', 2), ('Manjeet', 4)}

Example 2: Python zip enumerate

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

Example 3: Python zip() Dictionary

Python3

stocks = ['reliance', 'infosys', 'tcs']

prices = [2175, 1127, 2750]

new_dict = {stocks: prices for stocks,

            prices in zip(stocks, prices)}

print(new_dict)

Output:

{'reliance': 2175, 'infosys': 1127, 'tcs': 2750}

How to unzip? 

Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator.

Python3

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

roll_no = [4, 1, 3, 2]

marks = [40, 50, 60, 70]

mapped = zip(name, roll_no, marks)

mapped = list(mapped)

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

print(mapped)

print("\n")

namz, roll_noz, marksz = zip(*mapped)

print("The unzipped result: \n", end="")

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 be executed using zip, be it student database or scorecard or any other utility that requires mapping of groups. A small example of scorecard is demonstrated below. 

Python3

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

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

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

What is zip function in pandas?

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.

What does zip do in NumPy?

If we want to bind or zip the data of different array then we can go for zip function in python of NumPy. This function eliminates the need of class object if not required. We can easily map our data with any number of the array and this can be done very easily with the use of the zip() function.

What is difference between zip () and enumerate () Explain with example?

The Python Tutorials Blog The enumerate() function returns indexes of all items in iterables (lists, dictionaries, sets, etc.) whereas the zip() function is used to aggregate, or combine, multiple iterables.