can list comprehensions replace map?

Steven Bethard steven.bethard at gmail.com
Thu Jul 28 02:04:04 CEST 2005


David Isaac wrote:
> 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.

I almost never run into this situation, so I'd be interested to know why 
you need this.  Here's one possible solution:

py> import itertools as it
py> def zipfill(*lists):
... 	max_len = max(len(lst) for lst in lists)
... 	return zip(*[it.chain(lst, it.repeat(None, max_len - len(lst)))
...                  for lst in lists])
...
py> zipfill(range(4), range(5), range(3))
[(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, None), (None, 4, None)]

If you prefer, you can replace the call to zip with it.zip and get an 
iterator back instead of a list.

STeVe



More information about the Python-list mailing list