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)
use the builtin method reversed
arr = [5, 6, 8]
for i in reversed(range(0,len(arr))):
print(i,arr[i])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With