The Python Oracle

Loop backwards using indices

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle2

--

Chapters
00:00 Question
00:23 Accepted answer (Score 527)
00:45 Answer 2 (Score 239)
00:59 Answer 3 (Score 49)
01:15 Answer 4 (Score 19)
01:34 Thank you

--

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

Accepted answer links:
[here]: https://docs.python.org/library/function...
[here]: https://docs.python.org/3/library/stdtyp...

--

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