Comparison of map and list compression

Asked 2 years ago, Updated 2 years ago, 72 views

Is there any particular rule for when to use map() and when to use list embedding? Which of the two is the more efficient and Python way?

python map list-comprehension

2022-09-21 18:22

1 Answers

And Python developers usually prefer lists because they are more readable.

The speed difference is as follows.

$ 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) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop
$ 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 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop


2022-09-21 18:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.