[Tutor] Python Idioms?

Dave Angel davea at davea.name
Wed Apr 1 14:45:44 CEST 2015


On 04/01/2015 12:50 AM, Jim Mooney wrote:
> I'm looking at this and can't see how it works, although I understand
> zipping and unpacking. The docs say it's a Python idiom. Does "idiom" mean
> it works in a special way so I can't figure it out from basic principles?
> It looks to me like the iterator in the list gets doubled, so the zip
> should make it [(1,1),(2,2),(3,3),... ], not [(1,2),(3,4),...]
>
> What am I missing here?
>
>>>> s = [1,2,3,4,5,6,7,8]
>>>> list(zip(*[iter(s)]*2))
>>>> [(1, 2), (3, 4), (5, 6), (7, 8)]
>
> https://docs.python.org/3/library/functions.html#zip
>


In that same thread, Peter Otten posted the following, which I think is 
probably a bit clearer:


 >>> flat_pairs = ['broadcast', '"d8on"', 'broadcast', '"d11on"']
 >>> it = iter(flat_pairs)
 >>> pairs = list(zip(it, it))
 >>> pairs

That does exactly the same thing, but in the first one you can replace 
the '2' with a variable, to make variable sized tuples.

In both cases, the trick is that the same iterator is used twice in the 
expression, so even though zip is taking one from each, there are no 
duplications.

If you know the original data is a list, or at least that it can do 
slices, then you can do Alan's suggestion:


zip(s[::2],s[1::2])

Or you could try:

from itertools import islice

pairs = zip(islice(s, 0, 9999, 2), islice(s, 1, 9999, 2))



-- 
DaveA


More information about the Tutor mailing list