简体   繁体   中英

Why the code has different behavior in python2 and python3?

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))

In Python 3, zip (and some other functions, eg 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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM