File tree Expand file tree Collapse file tree 3 files changed +36
-0
lines changed Expand file tree Collapse file tree 3 files changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ # List Comprehension
2
+ This directory is here to show the Speed Difference between using
3
+ Dictionary Comprehension vs. a For Loop to create a dictionary
4
+
5
+ ## Executing
6
+ In a UNIX terminal, run:
7
+
8
+
9
+ ```
10
+ time python dict-loop.py
11
+
12
+ real 0m3.087s
13
+ user 0m2.762s
14
+ sys 0m0.324s
15
+ ```
16
+
17
+ ```
18
+ time python dict-comp.py
19
+
20
+ real 0m2.581s
21
+ user 0m2.252s
22
+ sys 0m0.328s
23
+ ```
24
+
25
+
26
+ Here we see that the dictionary comprehension is about 20% faster
27
+ than the for loop method. Again, this is a case-by-case scenario,
28
+ but generally the Dictionary comprehension will probably be faster.
29
+ There are probably cases where dictionary comprehension is slower,
30
+ but at the end of the day, comprehensions are generally used for
31
+ more concise code rather than for speed.
Original file line number Diff line number Diff line change
1
+ d = {i : i ** 2 for i in range (1 , 10_000_001 )}
Original file line number Diff line number Diff line change
1
+ d = {}
2
+
3
+ for i in range (1 , 10_000_001 ):
4
+ d [i ] = i ** 2
You can’t perform that action at this time.
0 commit comments