snippetpythonCriticalCanonical
How do I reverse a list or loop over it backwards?
Viewed 0 times
howbackwardsoverreverselistloop
Problem
How do I iterate over a list in reverse in Python?
See also: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
See also: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
Solution
To get a new reversed list, apply the
To iterate backwards through a list:
reversed function and collect the items into a list:>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]To iterate backwards through a list:
>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0Code Snippets
>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0Context
Stack Overflow Q#3940128, score: 1734
Revisions (0)
No revisions yet.