making zip with list comprehensions

Jonathan Hogg jonathan at onegoodidea.com
Tue Jul 9 06:06:54 EDT 2002


On 9/7/2002 10:56, in article oryW8.234$xm1.54155 at news0.telusplanet.net,
"Ian McMeans" <imcmeans at home.com> wrote:

> I was idly trying to replicate zip's (the function) behavior using list
> comprehensions, but I couldn't do it.
> 
> Can anyone? I came up with these, but they're ugly.
> 
>>>> [(x,y) for x in ['a','b','c'] for y in ['d','e','f'] if
> ['a','b','c'].index(x) == ['d','e','f'].index(y)]
> [('a', 'd'), ('b', 'e'), ('c', 'f')]
> 
> This is ugly because it loops far too many times =)
> 
>>>> [ (['a','b','c'][x], ['d','e','f'][x]) for x in range(3)]
> [('a', 'd'), ('b', 'e'), ('c', 'f')]
> 
> This isn't so bad. Does anyone have better suggestions?
> 
> 

Best I could come up with is:

>>> xs = [ 'a', 'b', 'c' ]
>>> ys = [ 'd', 'e', 'f' ]
>>> 
>>> [ ( x, yi.next() ) for yi in (iter(ys),) for x in xs ]
[('a', 'd'), ('b', 'e'), ('c', 'f')]
>>> 

I think the lack of a clean way of doing lockstep iteration is exactly why
'zip' was invented ;-)

-thou-shalt-not-use-for-in-list-comprehensions-to-do-let-bindings-ly y'rs,

Jonathan




More information about the Python-list mailing list