Using a simple for is faster than list comprehesion . It is almost 2 times faster. Check the results below:
Using list comprehension : 58 usec
moin@moin-pc :~$ python -m timeit "[i for i in range(1000)]" 10000 loops, best of 3: 58 usec per loop
Using a for loop: 37.1 usec
moin@moin-pc :~$ python -m timeit "for i in range(1000): i" 10000 loops, best of 3: 37.1 usec per loop
But in your case, for takes longer than understanding the list, not because YOUR for loop is slower. But because of .append() you are using code.
From append() to for loop`: 114 usec
moin@moin-pc :~$ python -m timeit "my_list = []" "for i in range(1000): my_list.append(i)" 10000 loops, best of 3: 114 usec per loop
Which clearly shows that it is .append() , which takes twice as much time spent on the for loop .
However, on storing the "list.append" in different variable : 69.3 usec
moin@moin-pc :~$ python -m timeit "my_list = []; append = my_list.append" "for i in range(1000): append(i)" 10000 loops, best of 3: 69.3 usec per loop
There is a significant performance improvement over the last case in the comparison above, and the result is quite comparable to the result of list comprehension . This means that instead of calling my_list.append() performance can be improved each time by storing a function reference in another variable ie append_func = my_list.append and making a call using this variable append_func(i) .
Which also proves that it is faster to call a class function stored in a variable compared to directly calling a function using a class object .
Thank you Stefan for recording the latest case.