Python - getting a list of numbers from N to 0

What is the best way to get a list [N, N-1, ..., 0]in python? I have 2 ways to think

>>> 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]
+4
source share
5 answers
range(N, -1, -1) is better

You can see that 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 first do the same thing range(N, -1, -1)as and then invert the list, so it takes more time.

+9
source

If your list of numbers is potentially large or you really don’t need this list, but just sorting through something by range, you can avoid actually creating the list with

xrange(N, -1, -1)

Rob , Python 3 ( , ), Python 2 range(), xrange() .

+2
import timeit

print timeit.timeit("range(10)[::-1]", number=10000000)
print timeit.timeit("range(9, -1, -1)", number=10000000)

Exit on my car

2.99922299385
2.24587512016

It seems that the second one is a bit faster, so use range(9, -1, -1)

+1
source

If you want to use a range, do the following:

range(n, -1, -1)

As others have shown, this is faster.

Personally, for the loopback, I prefer to use the built-in functions reversedin combination with enumerate:

for i, v in enumerate(reversed(mylist))

This is a bit more readable and you get both index and value :)

0
source

Your second method is to touch faster:

%timeit range(9,-1,-1)
> 1000000 loops, best of 3: 496 ns per loop

%timeit range(10)[::-1]
> 1000000 loops, best of 3: 659 ns per loop
0
source

All Articles