Zip with a list comprehension
imbosol at aerojockey.com
Fri Dec 10 23:09:01 CET 2004
Matt Gerrans wrote:
> This is probably so easy that I'll be embarrassed by the answer.
> enhancing and refactoring some old code, I was just changing some
> list comprehensions, but I couldn't see any easy way to change a
zip() to a
> list comprehension. Should I just let those sleeping dogs lie?
> comprehensions seem more readable than map(), but if the list
> that does the equivalent of zip() is less expressive than zip(), I'll
> with zip()).
I don't recall seeing zip on the list of things that were considered
bad for Python 3K, probably because it's not functional programming (a
la map, reduce, and filter) but rather just list manipulation.
I can't think of a good way to replace zip with a list comp, and I
doubt there is such a way. Think about it: a list comp is semantically
equivalent to a certain for loop (or loops, perhaps with some if-blocks
in there as well). A list comp can do only what a for loop can do,
Well, zip was created to address a deficiency in for-looping, namely
that it was unwieldy to loop through two lists side-by-side. I suspect
that, if there were a simple way to accomplish what zip does in a list
comp, there would have also been an easy way to do it with for loops,
and therefore zip would not have had any reason to exist.
So, unless the BDFL waves his magic wand and adds some new syntax for
for loops (unlikely), I think you can operate under the assumption that
zip will be Python 3000 Certified (tm).
Having said that, you might want to consider using itertools.izip
instead. It works just like zip, but returns an iterator instead of a
list. Good for those length-ten-million lists you wanted to iterate
More information about the Python-list