Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - getting list of numbers N to 0 [closed]

Tags:

python

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]
like image 936
Sourabh Avatar asked Nov 07 '13 15:11

Sourabh


1 Answers

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.

like image 130
Ankur Ankan Avatar answered Sep 26 '22 17:09

Ankur Ankan