Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
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)
edited by

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.

Learn more about Python from an expert. Enroll in our Python Course!

Related questions

0 votes
1 answer
asked Jun 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 22, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...