Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 630f1ef

Browse files
committed
add dictionary comprehension
1 parent bdcb785 commit 630f1ef

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

‎comprehension/dictionary/README.md

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

‎comprehension/dictionary/dict-comp.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
d = {i : i**2 for i in range(1, 10_000_001)}

‎comprehension/dictionary/dict-loop.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
d = {}
2+
3+
for i in range(1, 10_000_001):
4+
d[i] = i**2

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /