+ 2
How do I iterate over a list in reverse order?
Without touching the original/initial list.
11 Réponses
+ 4
suppose original list is
a=[1,2,3]
b=a
Now
for i in b[::-1]:
+ 3
If you mean looping through a list in reverse, use:
for x in reversed(range(len(list))):
+ 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
+ 3
Abhay Why bother with the copy at all?
+ 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.
+ 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
+ 2
David Carroll questions says without touching the original list so for that you need to make a copy if i am not wrong!
+ 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. 😉👌
+ 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.
+ 1
Use "reversed" keyword
0
See the code in my profile.