|
| 1 | +# List Comprehension |
| 2 | +This directory is here to show the Speed Difference between using |
| 3 | +List Comprehension vs. calling append() in a For Loop to create a list |
| 4 | + |
| 5 | +## Executing |
| 6 | +In a UNIX terminal, run: |
| 7 | + |
| 8 | +``` |
| 9 | +time python list-append-loop.py |
| 10 | +``` |
| 11 | +real 0m11.381s |
| 12 | +user 0m10.553s |
| 13 | +sys 0m0.824s |
| 14 | + |
| 15 | +``` |
| 16 | +time python list-comp.py |
| 17 | +``` |
| 18 | +real 0m4.228s |
| 19 | +user 0m3.428s |
| 20 | +sys 0m0.800s |
| 21 | + |
| 22 | + |
| 23 | +Here we see that the list comprehension was almost 3x as fast |
| 24 | +as the `list.append()` for loop. This is because everytime the |
| 25 | +append() method is called, it has to be looked up by the Interpreter, |
| 26 | +whereas the list comprehension can do it all at once. |
| 27 | + |
| 28 | +### Disclaimer |
| 29 | +Since this is a very simple example where we are just creating a list of |
| 30 | +numbers with the range() function, we can actually just cast the result |
| 31 | +of the range() function to a list and get even faster speed than the |
| 32 | +list comprehension. |
| 33 | + |
| 34 | +To show a more practical example where you can't just cast it: |
| 35 | + |
| 36 | +``` |
| 37 | +time python list-append-loop2.py |
| 38 | +``` |
| 39 | + |
| 40 | +real 0m29.756s |
| 41 | +user 0m28.875s |
| 42 | +sys 0m0.880s |
| 43 | + |
| 44 | + |
| 45 | +``` |
| 46 | +time python list-comp2.py |
| 47 | +``` |
| 48 | + |
| 49 | +real 0m21.932s |
| 50 | +user 0m21.031s |
| 51 | +sys 0m0.900s |
| 52 | + |
| 53 | +In this practical example, we see that the list comprehension finished |
| 54 | +in about 2/3 of the time it took the for loop append() method, still |
| 55 | +significantly faster! |
| 56 | + |
| 57 | +All in all, it depends on the example, but list comprehensions are often |
| 58 | +faster than using a loop. |
0 commit comments