substituting list comprehensions for map()

Anh Hai Trinh anh.hai.trinh at gmail.com
Mon Nov 2 23:24:12 EST 2009


> On the other hand, list comps using an if clause can't be written as pure
> maps. You can do this:
>
> [func(x) for x in seq if cond(x)]
>
> filter(cond, map(func, seq))
>
> but the second version may use much more temporary memory if seq is huge
> and cond very rarely true.

You could use ifilter, imap there to reduce memory.


> And I don't think you could write this as a single map:
>
> [func(a, b) for a in seq1 for b in seq2]

Oh you surely could:

  seq1, seq2 = [1,2,3], [4,5,6]

  [a+b for a in seq1 for b in seq2]
->[5, 6, 7, 6, 7, 8, 7, 8, 9]

  from itertools import product
  map(sum, product(seq1, seq2))
->[5, 6, 7, 6, 7, 8, 7, 8, 9]


Peace,

----aht



More information about the Python-list mailing list