Skip to content

Commit 6ff45c8

Browse files
committed
create repo, add some list comprehension examples
1 parent 2cbfd23 commit 6ff45c8

File tree

6 files changed

+67
-0
lines changed

6 files changed

+67
-0
lines changed

comprehension/list/README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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.

comprehension/list/cast-list.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
l = list(range(100000000))
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
l = []
2+
for i in range(100000000):
3+
l.append(i)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
l = []
2+
for i in range(1000000):
3+
l.append(i**2)

comprehension/list/list-comp.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
l = [x for x in range(100000000)]

comprehension/list/list-comp2.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
l = [x**2 for x in range(1000000)]

0 commit comments

Comments
 (0)