Python List Comprehension Vs. Map -
is there reason prefer using map() on list comprehension or vice versa? either of them more efficient or considered more pythonic other?
map may microscopically faster in cases (when you're not making lambda purpose, using same function in map , listcomp). list comprehensions may faster in other cases , (not all) pythonistas consider them more direct , clearer.
an example of tiny speed advantage of map when using same function:
$ python -mtimeit -s'xs=range(10)' 'map(hex, xs)' 100000 loops, best of 3: 4.86 usec per loop $ python -mtimeit -s'xs=range(10)' '[hex(x) x in xs]' 100000 loops, best of 3: 5.58 usec per loop an example of how performance comparison gets reversed when map needs lambda:
$ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)' 100000 loops, best of 3: 4.24 usec per loop $ python -mtimeit -s'xs=range(10)' '[x+2 x in xs]' 100000 loops, best of 3: 2.32 usec per loop
Comments
Post a Comment