Member-only story
Python — Why Python list are slower when sorted
2 min readDec 15, 2021
In the following code, I create two lists with the same values: one list unsorted (s_not), the other sorted (s_yes). The values are created by randint(). I run some loop for each list and time it.
import random
import timefor x in range(1,9): r = 10**x # do different val for the bound in randint()
m = int(r/2) print("For rand", r) # s_not is non sorted list
s_not = [random.randint(1,r) for i in range(10**7)] # s_yes is sorted
s_yes = sorted(s_not) # do some loop over the sorted list
start = time.time()
for i in s_yes:
if i > m:
_ = 1
else:
_ = 1
end = time.time()
print("yes", end-start) # do the same to the unsorted list
start = time.time()
for i in s_not:
if i > m:
_ = 1
else:
_ = 1
end = time.time()
print("not", end-start) print()
With output:
For rand 10
yes 1.0437555313110352
not 1.1074268817901611For rand 100
yes 1.0802974700927734
not 1.1524150371551514For rand 1000
yes 2.5082249641418457
not 1.129960298538208For rand 10000
yes 3.145440101623535
not 1.1366300582885742For rand 100000
yes 3.313387393951416
not…