Python zip()

Python zip() builtin function is used to make an iterator that aggregates elements from each of the iterables as tuples.

In this tutorial, we will learn about the syntax of Python zip() function, and learn how to use this function with the help of examples.

Syntax

The syntax of zip() function is

zip(*iterables)

where

ParameterRequired/OptionalDescription
iterablesRequiredOne or more iterable objects.

Returns

The function returns an iterator object.

Example

Zip Iterables

In this example, we take two lists: names and count; and zip them using zip() function.

Python Program

names = ['apple', 'banana', 'cherry']
count = [25, 31, 85]
result = zip(names, count)
for item in result:
    print(item)
Try Online

Output

('apple', 25)
('banana', 31)
('cherry', 85)

Zip Iterables of Different Lengths

In this example, we take two lists: names and count where length of first list is 2, and length of second list is 3. When we zip iterables of different lengths, the length of resulting iterable is the length of the smallest iterable.

Python Program

names = ['apple', 'banana']
count = [25, 31, 85]
result = zip(names, count)
for item in result:
    print(item)
Try Online

Output

('apple', 25)
('banana', 31)

Rest of the elements in the longer iterables are ignored.

Conclusion

In this Python Tutorial, we have learnt the syntax of Python zip() builtin function, and also learned how to use this function, with the help of Python example programs.