Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The zip() function in Python 3 [duplicate]

Tags:

python

I know how to use the zip() function in Python 3. My question is regarding the following which I somehow feel quite peculiar:

I define two lists:

lis1 = [0, 1, 2, 3] lis2 = [4, 5, 6, 7] 

and I use the zip() on these in the following ways:

1. test1 = zip( lis1, lis2)  2. test2 = list(zip(lis1, lis2)) 

when I type test1 at the interpreter, I get this:

"zip object at 0x1007a06c8" 

So, I type list(test1) at the interpreter and I get the intended result, but when I type list(test1) again, I get an empty list.

What I find peculiar is that no matter how many times I type test2 at the interpreter I always get the intended result and never an empty list.

like image 918
dhaliman Avatar asked Jul 28 '15 18:07

dhaliman


People also ask

Does zip remove duplicates Python?

Answer. If the list passed to the zip() function contains duplicate data, the duplicate created as part of the list comprehension will be treated as an update to the dictionary and change the value associated with the key. No error will be reported.

What is the use of zip () function in Python?

Python zip() Function The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

What is the role of the * operator within the zip () function?

Basically, it passes the contents of the lists as arguments.


1 Answers

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))  zipped_list = test2[:]  zipped_list_2 = list(test2) 
like image 73
Brien Avatar answered Nov 16 '22 00:11

Brien