Search code examples
pythonlistrangereverse

Print a list in reverse order with range()?


How can you produce the following list with range() in Python?

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Solution

  • Use reversed() function (efficient since range implements __reversed__):

    reversed(range(10))
    

    It's much more meaningful.

    Update: list cast

    If you want it to be a list (as @btk pointed out):

    list(reversed(range(10)))
    

    Update: range-only solution

    If you want to use only range to achieve the same result, you can use all its parameters. range(start, stop, step)

    For example, to generate a list [3, 2, 1, 0], you can use the following:

    range(3, -1, -1)
    

    It may be less intuitive, but it works the same with less text. This answer by @Wolf indicates this approach is slightly faster than reversed.