Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Why is builtin sorted() slower for a list containing descending numbers if each number appears twice consecutively?

$
0
0

I sorted four similar lists. List d consistently takes much longer than the others, which all take about the same time:

a:  33.5 msb:  33.4 msc:  36.4 msd: 110.9 ms

Why is that?

Test script (Attempt This Online!):

from timeit import repeatn = 2_000_000a = [i // 1 for i in range(n)]  # [0, 1, 2, 3, ..., 1_999_999]b = [i // 2 for i in range(n)]  # [0, 0, 1, 1, 2, 2, ..., 999_999]c = a[::-1]                     # [1_999_999, ..., 3, 2, 1, 0]d = b[::-1]                     # [999_999, ..., 2, 2, 1, 1, 0, 0]for name in 'abcd':    lst = eval(name)    time = min(repeat(lambda: sorted(lst), number=1))    print(f'{name}: {time*1e3 :5.1f} ms')

Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>