Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
keyword
zip
iterable
iterator

How does zip() work in Python?

Educative Answers Team

What is zip()?

The zip() method in python returns a zip object by taking in iterables, like lists or strings, and aggregating them into tuples.

  • No parameter: When given no iterable as a parameter, zip() returns an empty iterator.

  • Single parameter: When given a single iterable argument, zip() returns an iterator of tuples with each tuple only having one element.

  • Multiple parameters: When given multiple iterables, zip() returns an iterator of tuples with each tuple having multiple elements.

serialNumbers = [1, 2, 3]
names = ['Sarah', 'John', 'Harry']

# No iterables are passed
result = zip()
print(result)

# With a single iterable
result = zip(serialNumbers)
print(result)

# With multiple iterables
result = zip(serialNumbers, names)
print(result)

Purpose

The purpose of this function is to map the elements of iterables to the same indexes in the tuples.

svg viewer
serialNumbers = [1, 2, 3]
names = ['Sarah', 'John', 'Harry']

result = zip(serialNumbers, names)
print(result)

# Now, to get a clear picture of how zip() 
# function is mapping both the iterables:
for a,b in zip(serialNumbers, names):
    print(a,b)

Reading the result

In order to obtain the output in a readable format, you can use tuple() to view the result in the form of tuples. You may also use list() or set() functions, as seen below:

serialNumbers = [1, 2, 3]
names = ['Sarah', 'John', 'Harry']

result = zip(serialNumbers, names)

# Use tuple() function to read the result
print(tuple(result))


# Converting itertor to list
resultList = list(result)
print(resultList)

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

What happens with input iterables of different lengths?

The iterator returned form zip() stops when one of the input iterable is exhausted.

serialNumbers = [1, 2, 3, 4, 5]    # length = 5
names = ['Sarah', 'John', 'Harry'] # length = 3

for a,b in zip(serialNumbers, names):
    print(a,b)

RELATED TAGS

python
keyword
zip
iterable
iterator
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring