Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody give me an example for the zip() function in Python?

Tags:

python-2.7

In Python's document, it says the following things for the zip function:

"The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n)."

I have a difficulty in understanding the zip(*[iter(s)]*n) idiom. Can any body give me an example on when we should use that idiom?

Thank you very much!

like image 769
weilezc1 Avatar asked Sep 05 '25 15:09

weilezc1


2 Answers

It's 2020, but let me leave this here for reference.

The zip(*[iter(s)]*n) idiom is used to split a flat list into chunks.

For example:

>>> mylist = [1, 2, 3, 'a', 'b', 'c', 'first', 'second', 'third']
>>> list(zip(*[iter(mylist)]*3))
[(1, 2, 3), ('a', 'b', 'c'), ('first', 'second', 'third')]

The idiom is analyzed here.

like image 153
peter.slizik Avatar answered Sep 09 '25 17:09

peter.slizik


I don't know what documentation you're using, but this version of zip() documentation, has this example:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

It interpolates two lists together, in respective order, and it also has an "unzip" feature

And since you asked, here's a slightly more understandable example:

>>> friends = ["Amy", "Bob", "Cathy"]
>>> orders = ["Burger", "Pizza", "Hot dog"]
>>> friend_order_pairs = zip(x, y)
>>> friend_order_pairs
[("Amy", "Burger"), ("Bob", "Pizza"), ("Cathy", "Hot dog")]
like image 41
Kache Avatar answered Sep 09 '25 17:09

Kache