Does PEP 3106 offer a slower path? What for?

I recently had to convert dictionary values ​​to a list in Python 3.6 and use the case where this should happen a lot.
Trying to be a good guy, I wanted to use a solution that is close to PEP. Now PEP 3106 offers

list(d.keys()) 

which obviously works fine - but using timeit on my windows 7 machine, I see

 >python -m timeit "[*{'a': 1, 'b': 2}.values()]" 1000000 loops, best of 3: 0.249 usec per loop >python -m timeit "list({'a': 1, 'b': 2}.values())" 1000000 loops, best of 3: 0.362 usec per loop 

I suppose there is an advantage in the latest version, because why else does PEP offer a slower one.

So, here is my question: what is the advantage of the latest version compared to the first?

+5
source share
1 answer

The answer is that the faster syntax was first introduced in PEP 448 in 2013, and PEP 3106 , this link was written in 2006, so even if it happens faster in real time, it did not exist when PEP was written.

As others have pointed out, the role of PEP is not to create a template for the fastest code - in general, the code in PEP will strive to be as simple and clear as possible, because the examples usually relate to understanding the concepts and not reaching the best possible results, therefore, even if the syntax really existed at that time and faster in a real (and reliable) way, it still might not be used.

A little extra testing with large values:

 python -m timeit -s "x = [1]*10000" "[*x]" 10000 loops, best of 3: 44.6 usec per loop python -m timeit -s "x = [1]*10000" "list(x)" 10000 loops, best of 3: 44.8 usec per loop 

It actually shows the difference not twice, but rather at a flat price - I would suggest that this is the cost of searching for the built-in list() function. This is negligible in most real cases.

+9
source

Source: https://habr.com/ru/post/1275969/


All Articles