The Python Oracle

Loop backwards using indices

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow

--

Chapters
00:00 Loop Backwards Using Indices
00:18 Accepted Answer Score 559
00:34 Answer 2 Score 50
00:46 Answer 3 Score 253
00:57 Answer 4 Score 19
01:09 Thank you

--

Full question
https://stackoverflow.com/questions/8698...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #loops

#avk47



ACCEPTED ANSWER

Score 559


Try range(100,-1,-1), the 3rd argument being the increment to use (documented here).

("range" options, start, stop, step are documented here)




ANSWER 2

Score 253


In my opinion, this is the most readable:

for i in reversed(range(101)):
    print(i)



ANSWER 3

Score 50


for i in range(100, -1, -1)

and some slightly longer (and slower) solution:

for i in reversed(range(101))

for i in range(101)[::-1]



ANSWER 4

Score 19


Generally in Python, you can use negative indices to start from the back:

numbers = [10, 20, 30, 40, 50]
for i in xrange(len(numbers)):
    print numbers[-i - 1]

Result:

50
40
30
20
10