How do I iterate over a list in reverse order? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How do I iterate over a list in reverse order?

Without touching the original/initial list.

15th May 2020, 5:27 PM
akamhy
akamhy - avatar
11 Answers
+ 4
suppose original list is a=[1,2,3] b=a Now for i in b[::-1]:
15th May 2020, 5:37 PM
Abhay
Abhay - avatar
+ 3
If you mean looping through a list in reverse, use: for x in reversed(range(len(list))):
15th May 2020, 5:34 PM
Yamen Ghozlan
Yamen Ghozlan - avatar
+ 3
I see that you uused the word iterate,, but try this: nums =[9,6,5,8] Print(*nums[::-1], sep="\n") Output: 8 5 6 9
15th May 2020, 7:32 PM
Femi SONI Y
Femi SONI Y - avatar
+ 3
Abhay Why bother with the copy at all?
16th May 2020, 2:37 AM
David Carroll
David Carroll - avatar
+ 2
If you want to iterate a list in reverse without having to create a temp copy of the list, you can use the following options in this code: https://code.sololearn.com/cgz3QnsBd8Nf/ NOTE: Using list comprehensions / slicing will create a temp copy of the list.
15th May 2020, 7:31 PM
David Carroll
David Carroll - avatar
+ 2
Adding to the answer I provided before that won't work if you make changes to list b In example a=[1,2,3,4] b=a For i in b[::-1]: If you perform some operations on b that will be applied to a as well so the best would be to store a shallowcopy of a into b like b=a[:] now any changes made to b won't change the original list a
15th May 2020, 7:50 PM
Abhay
Abhay - avatar
+ 2
David Carroll questions says without touching the original list so for that you need to make a copy if i am not wrong!
16th May 2020, 8:10 AM
Abhay
Abhay - avatar
+ 2
Abhay Ah... I think we both read that question with different interpretations. 😉 You interpreted "without touching the original/initial list" as not _referencing_ the original list. That actually makes sense to me now. I interpreted it to mean without _modifying_ the original list. The problem is the use of the word "touching" makes this question ambiguous as both interpretations are valid. Thanks for clarifying. 😉👌
16th May 2020, 3:25 PM
David Carroll
David Carroll - avatar
+ 1
"Without touching"....do you mean..."...without changing the order of the original list? ...if so...just do:- a=[1,2,3] for i in a[::-1]: print(i) print(a).....# for comparison.
15th May 2020, 6:44 PM
rodwynnejones
rodwynnejones - avatar
+ 1
Use "reversed" keyword
17th May 2020, 1:42 AM
Awojobi Godfrey
Awojobi Godfrey - avatar
0
See the code in my profile.
17th May 2020, 2:24 AM
The.Anish.Singh
The.Anish.Singh - avatar