can list comprehensions replace map?
python at rcn.com
Wed Jul 27 20:00:03 EDT 2005
> > 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'?)
> Probably zip should change behaviour,and cover that case or at least
> have another like 'tzip' in the __builtins__ .Dunno, I always thought
> zip should not cut to the shortest list.
Heck no! For the core use case of lockstep iteration, it is almost
always a mistake to continue iterating beyond the length of the
shortest input sequence. Even for map(), the use cases are thin. How
many functions do something meaningful when one or more of their inputs
changes type and becomes a stream of Nones. Consider for example,
map(pow, seqa, seqb) -- what good can come of one sequence or the other
suddenly switching to a None mode?
As Andrew pointed out, if you really need that behavior, it can be
provided explicity. See the padNone() recipe in the itertools
documentation for an easy one-liner.
IMO, reliance on map's None fill-in feature should be taken as a code
smell indicating a design flaw (not always, but usually). There is a
reason that feature is missing from map() implementations in some other
In contrast, the existing behavior of zip() is quite useful. It allows
some of the input sequences to be infinite:
More information about the Python-list