Python zip object disappears after iteration?

General question about noob, but I really want to know the answer.

I donโ€™t know why the zip object just โ€œdisappearsโ€ after I try to iterate over it as a list: for example.

>>> A=[1,2,3] >>> B=['A','B','C'] >>> Z=zip(A,B) >>> list(Z) >>> [('C', 3), ('B', 2), ('A', 1)] >>> {p:q for (p,q) in Z} {1: 'A', 2: 'B', 3: 'C'} >>> {p:q for (p,q) in list(Z)} {} >>> list(Z) [] 

(this is in Python 3.4.2)

Does anyone help?

+6
source share
2 answers

There was a change of behavior between Python2 and Python3:
in python2, zip returns a list of tuples , while in python3 it returns an iterator .

The nature of the iterator is that once it iterates over the data, it points to an empty collection and the behavior you are experiencing.

python2

 Python 2.7.9 (default, Jan 29 2015, 06:28:58) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> A=[1,2,3] >>> B=['A','B','C'] >>> Z=zip(A,B) >>> Z [(1, 'A'), (2, 'B'), (3, 'C')] >>> list(Z) [(1, 'A'), (2, 'B'), (3, 'C')] >>> list(Z) [(1, 'A'), (2, 'B'), (3, 'C')] >>> list(Z) [(1, 'A'), (2, 'B'), (3, 'C')] >>> {p:q for (p,q) in Z} {1: 'A', 2: 'B', 3: 'C'} >>> Z [(1, 'A'), (2, 'B'), (3, 'C')] >>> Z [(1, 'A'), (2, 'B'), (3, 'C')] 

Python3

 Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> A=[1,2,3] >>> B=['A','B','C'] >>> Z=zip(A,B) >>> list(Z) [(1, 'A'), (2, 'B'), (3, 'C')] >>> list(Z) [] >>> 
+3
source

zip creates an object to repeat by results. It also means that it is exhausted after one iteration:

 >>> a = [1,2,3] >>> b = [4,5,6] >>> z = zip(a,b) >>> list(z) [(1, 4), (2, 5), (3, 6)] >>> list(z) [] 

You need to call zip(a,b) every time you want to use it, or save the result of list(zip(a,b)) and use it several times.

+3
source

Source: https://habr.com/ru/post/982160/


All Articles