bodn19888
bodn19888

Reputation: 167

the process of function zip() python

I want to ask a question about zip() in python.

Consider the following simple code to demonstrate zip().

a = ['1', '2', '3']
b = ['a', 'b', 'c']

for key, value in zip(a, b):
    print(key + value)

I know that the following output is produced:

1a
2b
3c

where each element in the corresponding lists are concatenated.

As a beginner in Python3, I understand the following about zip():

zip() creates a zip object, related to OOP that can be shown using list():

my_zip = zip(a, b)
print(my_zip)
print(list(my_zip))
>>> <zip object at 0xsomelocation>
>>>[('1', 'a'), ('2', 'b'), ('3', 'c')]

such that the zip object is a list of tuples.

My confusion is in this line from the original block of code, which I don't really understand:

for key, value in zip(a, b)

My interpretation is that as we are looping through our zip object, which has some innate __next__() method called on by our for loop, we loop through each tuple in turn.

For our first iteration of the loop, we get:

('1', 'a')

and python assigns '1' and 'a' to our variables key and value respectively. This is repeated until the end of the list dimensions i.e. 3 times.

Is this the correct interpretation of what is happening in our code?

Upvotes: 2

Views: 340

Answers (1)

abhiarora
abhiarora

Reputation: 10430

such that the zip object is a list of tuples.

zip() doesn't return a list of tuples. It returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

and python assigns '1' and 'a' to our variables key and value respectively. This is repeated until the end of the list dimensions i.e. 3 times.

Yes. Rest of your interpretation is correct.

BONUS:

zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.

Upvotes: 1

Related Questions