can list comprehensions replace map?

Andrew Dalke dalke at dalkescientific.com
Wed Jul 27 16:11:05 EDT 2005


David Isaac wrote:
> I have been generally open to the proposal that list comprehensions
> should replace 'map', but I ran into a need for something like
> map(None,x,y)
> when len(x)>len(y).  I cannot it seems use 'zip' because I'll lose
> info from x.  How do I do this as a list comprehension? (Or,
> more generally, what is the best way to do this without 'map'?)

If you know that len(x)>=len(y) and you want the same behavior as
map() you can use itertools to synthesize a longer iterator


>>> x = [1,2,3,4,5,6]        
>>> y = "Hi!"
>>> from itertools import repeat, chain
>>> zip(x, chain(y, repeat(None)))   
[(1, 'H'), (2, 'i'), (3, '!'), (4, None), (5, None), (6, None)]
>>> 

This doesn't work if you want the result to be max(len(x), len(y))
in length - the result has length len(x).

As others suggested, if you want to use map, go ahead.  It won't
disappear for a long time and even if it does it's easy to
retrofit if needed.

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list