2

When we use python2 to run the following code, The result is

[(1, 2), (2, 3), (3, 4)]
m: 1, n: 2
m: 2, n: 3
m: 3, n: 4

Otherwise, using python3

[(1, 2), (2, 3), (3, 4)]

I think the result of python3 doesn't make sense? anybody can tell me why?

a = [1, 2, 3]
b = [2, 3, 4]
c = zip(a,b)

print(list(c))

for (m,n) in list(c):
    print('m: {}, n: {}'.format(m, n))
1
  • 1
    Where is the difference? The results are exactly the same. The only difference is what zip returns but since convert to list anyway this doesn't matter. Commented Mar 31, 2020 at 14:14

2 Answers 2

6

In Python 3, zip (and some other functions, e.g. map) return one-shot iterators. So, what happens is this:

  • You define c = zip(a, b), but c is not being evaluated yet (meaning that the iteration over a and b does not happen at this point).
  • print(list(c)) iterates over the elements of c until it reaches the end of the iterator. c is now "exhausted":

    >>> a = [1, 2, 3]
    >>> b = [2, 3, 4]
    >>> c = zip(a,b)
    
    >>> print(list(c))
    [(1, 2), (2, 3), (3, 4)]
    
    >>> next(c)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    
  • See how calling next(c) raises StopIteration? That is exactly what happens when you call list(c) the second time, so it returns an empty list:

    >>> list(c)
    []
    

One solution to the dilemma is to convert the iterator to a list right away (and only once):

a = [1, 2, 3]
b = [2, 3, 4]
c = list(zip(a,b))

print(c)

for (m,n) in c:
    print('m: {}, n: {}'.format(m, n))
Sign up to request clarification or add additional context in comments.

Comments

-1

Your value c is being iterated over twice. Once when converted to a list in the first print, and a second time in the for loop.

In Python 2, zip(a,b) is returning a list, which can be iterated over multiple times no problem.

In Python 3, zip(a,b) is returning a zip object, which is an iterator. This iterator is effectively "used up" the first time you iterate through it, and when the for loop runs, it has no items left to yield and so the loop body doesn't execute

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.