What's the best way to get a list [N, N-1, ..., 0]
in python? I have 2 ways in mind
>>> range(10)[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(9, -1, -1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
range(N, -1, -1) is better
You can see it takes much less time:
N = 10000
%timeit range(N+1)[::-1]
1000000 loops, best of 3: 767 ns per loop
%timeit range(N, -1, -1)
1000000 loops, best of 3: 334 ns per loop
In range(N+1)[::-1]
, you are first doing the exact same thing as range(N, -1, -1)
and then inverting the list, that's why it takes more time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With