Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zip variable empty after first use

Tags:

Python 3.2

t = (1, 2, 3) t2 = (5, 6, 7) z = zip(t, t2)  for x in z:     print(x) 

Result:

(1, 5) (2, 6) (3, 7) 

Putting in EXACTLY the same loop immediately after, nothing is printed:

for x in z:     print(x) 

z still exists as <zip object at 0xa8d48ec>. I can even reassign the t, t2 to be zipped again, but then it only works once and only once, again.

Is this how its supposed to work? There's no mention in the docs about this.

like image 523
jason Avatar asked Jul 21 '13 21:07

jason


People also ask

What does zip (*) do in Python?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

Can I zip more than two lists Python?

The Python zip() function makes it easy to also zip more than two lists. This works exactly like you'd expect, meaning you just only need to pass in the lists as different arguments. What is this? Here you have learned how to zip three (or more) lists in Python, using the built-in zip() function!

How do you zip two tuples in Python?

12.5 Lists and tuples zip is a built-in function that takes two or more sequences and “zips” them into a list of tuples where each tuple contains one element from each sequence. In Python 3, zip returns an iterator of tuples, but for most purposes, an iterator behaves like a list.

How do you zip two lists in Python?

chain() + zip() This combination of these two functions can be used to perform this particular task.


1 Answers

That's how it works in python 3.x. In python2.x, zip returned a list of tuples, but for python3.x, zip behaves like itertools.izip behaved in python2.x. To regain the python2.x behavior, just construct a list from zip's output:

z = list(zip(t,t2)) 

Note that in python3.x, a lot of the builtin functions now return iterators rather than lists (map, zip, filter)

like image 68
mgilson Avatar answered Sep 17 '22 15:09

mgilson