I am going trough the docs of Python 3.X, I have doubt about List Comprehension speed of execution and how it exactly work.
Let's take the following example:
Listing 1
...
L = range(0,10)
L = [x ** 2 for x in L]
...
Now in my knowledge this return a new listing, and it's equivalent to write down:
Listing 2
...
res = []
for x in L:
res.append(x ** 2)
...
The main difference is the speed of execution if I am correct. Listing 1 is supposed to be performed at C language speed inside the interpreter, meanwhile Listing 2 is not.
But Listing 2 is what the list comprehension does internally (not sure), so why Listing 1 is executed at C Speed inside the interpreter & Listing 2 is not? Both are converted to byte code before being processed, or am I missing something?
pyc
. The Python source code is open, so if you read C, you can read through the algorithms corresponding to list comprehension. – Vedettadis
module to analyze byte codes. And no, second code snippet does much more. All in-between states have to available to interpreter on each iteration (even if they are not used).res.append
invokes a function call (and they are not that cheap in Python). List comprehensions allows you for much less that explicit loop, but due to this limitations it allows for much efficient implementation. – Benefic