List comprehension in Python is typically used to compute another list from one list, functionally, as a map/filter, or through loops. Previously looked up some related information, some people say that the list derivation is only the grammatical sugar, also has said that the list derivation is more efficient than the circulation and the Map/filter (only gave a test result, no correlation analysis), other valuable information did not find ... This is one of the questions asked by an interviewer, I think it is necessary to find out, so I would like to know to ask you the great God.
In the design philosophy of Python, there is the phrase "there should be one--and preferably only one--obvious way to do it." If there is no difference between the list derivation and the loop and the Map/filter implementation , should it not exist? Of course, the philosophy of Python also has "Beautiful is better than ugly.", it seems that it may be just for the sake of good looks ...
Reply content:
First of all, the map and list derivation efficiency is indeed higher than the loop,
Let's start with the list derivation, below is my test results in Ipython (test environment Python 2.7.10):
>>> long_list = range(1000)>>> a = []>>> %timeit for i in long_list: a.append(i+1)10000 loops, best of 3: 100 µs per loop>>> %timeit [i+1 for i in long_list]10000 loops, best of 3: 43.3 µs per loop
A little more efficient, to see the DIS module.
Python does not like FP, and Map/filter is inert, list comprehension is not.
Loops are much lower than list comprehension and difficult to understand. Compare: "Multiply all the elements in this list by two" and "Create an empty list B, add the result to the end of B by multiplying each element in the listing a by two."
PS: For every use case that can be implemented in a variety of ways, I can basically identify an optimal approach.