All discussion is about python 3.1.2; see Python docs for the source of my question.
I know what zip
does; I just don't understand why it can be implemented like this:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))
Let's say I call zip(c1, c2, c3)
. If I understand correctly, iterables is initially the tuple (c1, c2, c3).
The line iterables = map(iter, iterables)
converts it to an iterator that would return iter(c1), iter(c2), iter(c3) if iterated through.
Inside the loop, map(next, iterables)
is an iterator that would return next(iter(c1))
, next(iter(c2))
, and next(iter(c3))
if iterated through. The tuple
call converts it to (next(iter(c1)), next(iter(c2)), next(iter(c3))
, exhausting its argument (iterables
) on the very first call as far as I can tell. I don't understand how the while
loop manages to continue given that it checks iterables
; and if it does continue why the tuple
call doesn't return empty tuple (the iterator being exhausted).
I'm sure I'm missing something very simple..
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.
The "*" operator unpacks a list and applies it to a function. The zip function takes n lists and creates n-tuple pairs from each element from both lists: zip([iterable, ...]) This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. It is used to map the similar index of multiple containers so that they can be used just using a single entity.
One of the way to create Pandas DataFrame is by using zip() function. You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe. zip() function creates the objects and that can be used to produce single item at a time.
It looks like it's a bug in the documentation. The 'equivalent' code works in python2 but not in python3, where it goes into an infinite loop.
And the latest version of the documentation has the same problem: http://docs.python.org/release/3.1.2/library/functions.html
Looks like change 61361 was the problem, as it merged changes from python 2.6 without verifying that they were correct for python3.
It looks like the issue doesn't exist on the trunk documentation set, but you probably should report a bug about it at http://bugs.python.org/.
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