Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping backwards in python and getting the index

Tags:

python

There are multiple ways to loop back in python For example we have

arr=[5,6,8]
for i in range(len(arr)-1, -1, -1):
  print(i," ",arr[i])

which gives

2   8
1   6
0   5

I can solve what I need with that, but I am curious. There is another way to loop back which is

for im in arr[::-1]:
  print(im) 

Looks nice, right? This gives

8
6
5

My question is, using this second method is there a way to get not only the element but also the index? (the 2,1,0)

like image 842
KansaiRobot Avatar asked Sep 12 '25 21:09

KansaiRobot


2 Answers

use the builtin method reversed

arr = [5, 6, 8]
for i in reversed(range(0,len(arr))):
    print(i,arr[i])
like image 123
theunknownSAI Avatar answered Sep 15 '25 12:09

theunknownSAI


There's a builtin for that: reversed. This might be more readable and intuitive than using a range or slice with negative step.

For just the index, you can pass the range to reversed directly:

arr = list("ABC")

for i in reversed(range(len(arr))):
    print(i, arr[i])                   
# 2 C
# 1 B
# 0 A

For index and element, you have to collect the enumerate iterator into a list before reversing:

for i, x in reversed(list(enumerate(arr))):
    print(i, x)                
# 2 C
# 1 B
# 0 A
like image 25
tobias_k Avatar answered Sep 15 '25 10:09

tobias_k