Menu Close

Python zip() function

python zip function

In this python guide, we are going to learn all about the Python zip() function to return a zip object. In the previous tutorial, we have seen all about the Python vars() function to return dict attribute of the given Object.

zip function in Python

Python zip function is a built-in function that takes zero or more tables and aggregates them and returns them. zip() function in Python returns a zip object, which is an iterator of tuples, where the first item of each iterator is paired together.

If the iterator has a different length, Then the iterator with the least items decides the length of the new iterator.

Syntax:

The syntax of the zip function in Python is:-

zip(iterator 1, iterator 2, iterator 3, iterator 4, ....)

Parameters:

zip function in Python accepts zero or more iterators (list, tuple, string, etc).

Return Value:

The return value of the zip function is a zip object having mapped value to all the iterators or containers.

Example: Zip two lists with the same length


students = ["Vishvajit", "Vinay", "Jay", "Harshita", "Pankhudi"]
age = [24, 23, 21, 20, 23]

zip_object = zip(students, age)
print(set(zip_object))

Output

{('Vishvajit', 24), ('Pankhudi', 23), ('Harshita', 20), ('Jay', 21), ('Vinay', 23)}

Example:- Zip two lists with the different-2 length



x = [1, 2, 3, 4, 5, 6, 7]
y  = {'a', 'b', 'c'}
z = ('x', 'y', 'z')
result = zip(x, y, z)
for i in result:
    print(i)

Output

(1, 'c', 'x')
(2, 'b', 'y')
(3, 'a', 'z')

Example:- Convert zip object to dictionary


students = ["Vishvajit", "Vinay", "Jay", "Harshita", "Pankhudi"]
age = [24, 23, 21, 20, 23]

zip_object = zip(students, age)

dictionary = {student: age for student, age in zip_object}
print(dictionary)

Output

{'Vishvajit': 24, 'Vinay': 23, 'Jay': 21, 'Harshita': 20, 'Pankhudi': 23}

Example:- zip() function with enumerate() function


students = ["Vishvajit", "Vinay", "Jay", "Harshita", "Pankhudi"]
age = [24, 23, 21, 20, 23]

# creating enumerate object
enumerate_object = enumerate(zip(students, age))

# iterate through each object of enumerate object
for i in enumerate_object:
    print(i)

Output

(0, ('Vishvajit', 24))
(1, ('Vinay', 23))
(2, ('Jay', 21))
(3, ('Harshita', 20))
(4, ('Pankhudi', 23))

Conclusion

In this article, you have learned all about the Python zip function to return the zip object. zip object is an iterator of tuples that can be iterated through for loop. I hope this article will help you. If you like this article, please share and keep visiting for further Python tutorials.

Python built-in functions


For more information:- Click Here

Thanks for your valuable time … 🧑‍💻🧑‍💻❤️❤️

Python type() Function
Python vars() Function

Related Posts