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.
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.
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!
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.
chain() + zip() This combination of these two functions can be used to perform this particular task.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With