Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (33.1k 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 (106k 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.6k points)
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 22, 2019 in Python by Sammy (47.6k 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!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...