0 votes
1 view
in Python by (33.2k points)

So I can start from len(collection) and end in collection[0]. I also want to be able to access the loop index.

1 Answer

0 votes
by (107k points)

There are many ways to do this problem:-

The first thing you can do is use build in reverse function.

a = ["abc", “def", "ghi"]

for i in reversed(a):

 print(i)

image

  • If you want to print answer with its actual index then you can use enumerate() and pass it to reverse function:-

a = ["abc", “def”, "ghi"] 

for i, e in reversed(list(enumerate(a))):

print(i, e)

image

  • Another thing you can do this by slicing method:-

a = ["abc", “def”, "ghi"] 

for item in a[::-1]: 

print(item)

image

The [::-1] slice reverses the list in the for loop but it will never modify your list permanently.

Related questions

0 votes
1 answer
asked Jun 26, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Jul 22, 2019 in Python by Sammy (47.8k points)
+2 votes
3 answers
asked May 21, 2019 in Python by Aditya98 (1.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...