Are list-comprehensions and functional functions faster than “for loops”?

后端 未结 7 1433
梦如初夏
梦如初夏 2020-11-22 01:48

In terms of performance in Python, is a list-comprehension, or functions like map(), filter() and reduce() faster than a for loop? Why

相关标签:
7条回答
  • 2020-11-22 02:23

    If you check the info on python.org, you can see this summary:

    Version Time (seconds)
    Basic loop 3.47
    Eliminate dots 2.45
    Local variable & no dots 1.79
    Using map function 0.54
    

    But you really should read the above article in details to understand the cause of the performance difference.

    I also strongly suggest you should time your code by using timeit. At the end of the day, there can be a situation where, for example, you may need to break out of for loop when a condition is met. It could potentially be faster than finding out the result by calling map.

    0 讨论(0)
提交回复
热议问题