pythonlistreverse

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


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