简体   繁体   中英

Python - backwards iteration through range in list

I'd like to search backwards through a list

This is code that I read in other posts should work

ls = [1, 2, 3]

for i in range(len(ls)-1, 0, -1):
    print(i)

The output would be:

2
1

Wheras if I use this code:

ls = [1, 2, 3]

for i in range(len(ls)-1, -1, -1):
    print(i)

The output is:

2
1
0

Why is it that range(len(ls)-1, 0, -1) skips an element, and why is it recommended as a solution for backwards iteration (rather than range(len(ls)-1, -1, -1) )?

If you don't mind the index being negative, you can do:

a = [1,2,3]
for i in range(-1, -1*(len(a)+1), -1):
    print(i, a[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM