4 ms·
Its not the looping itself that is slow in the article you linked, its that every element is appended to the list. If you use a list comprehension its even fast
by tweakimp 4y ago
Its not the looping itself that is slow in the article you linked, its that every element is appended to the list.
If you use a list comprehension its even faster and it still loops over all elements of the list.
- winrid 4y agoNo, AFAIK each for loop iteration appends and pops the stack in the interpreter, while map loops all entirely in the native implementation of the interpreter itself.
- masklinn 4y agoHere is the decompilation of the listcomp [x for x in range(5)] : RESUME 0 BUILD_LIST LOAD_FAST FOR_ITER 4 STORE_FAST (x) LOAD_FAST (x) LIST_APPEND JUMP_BACKWARDS 5 RETURN_VALUE As you can see from the third last instruction, a listcomp does append individual elements to the list. What it doesn’t need to do is call a method to do so (let alone lookup the corresponding method).