Last active
August 29, 2015 14:06
-
-
Save yeukhon/daf280283a88e15263b1 to your computer and use it in GitHub Desktop.
list extend vs nested loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
>>> a = [[1,2], [3,3], [4]] | |
>>> o = [] | |
>>> for x in a: | |
... o.extend(x) | |
... | |
>>> o | |
[1, 2, 3, 3, 4] | |
>>> [y for x in a for y in x] | |
[1, 2, 3, 3, 4] | |
>>> | |
""" | |
import time | |
# Creates 10,000 buckets each contains 1000 integers | |
random_array = [ [x for x in xrange(0, 1000)] for x in xrange(0, 10000) ] | |
output = [] | |
t1 = time.time() | |
for x in random_array: | |
output.extend(x) | |
t2 = time.time() | |
print(t2-t1) | |
t3 = time.time() | |
[y for sub_array in random_array for y in sub_array] | |
t4 = time.time() | |
print(t4-t3) | |
""" | |
ywong:tmp ywong$ python p.py | |
0.0799720287323 | |
0.858078956604 | |
ywong:tmp ywong$ python p.py | |
0.0888578891754 | |
0.858464002609 | |
ywong:tmp ywong$ python p.py | |
0.0784840583801 | |
0.870872974396 | |
Increase the size of each bucket to 10,000 | |
ywong:tmp ywong$ python p.py | |
0.796358108521 | |
9.03610396385 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment