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

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

Leave a Comment