HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I reverse a list or loop over it backwards?

Submitted by: @import:stackoverflow-api··
0
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)?

Solution

To get a new reversed list, apply the 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
0

Code 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
0

Context

Stack Overflow Q#3940128, score: 1734

Revisions (0)

No revisions yet.