Print a list in reverse order with range()?

前端 未结 19 795
长发绾君心
长发绾君心 2020-11-30 17:09

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

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
19条回答
  •  醉酒成梦
    2020-11-30 17:42

    use reversed() function:

    reversed(range(10))
    

    It's much more meaningful.

    Update:

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

    list(reversed(range(10)))
    

    Update:

    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 [5,4,3,2,1,0], you can use the following:

    range(5, -1, -1)
    

    It may be less intuitive but as the comments mention, this is more efficient and the right usage of range for reversed list.

提交回复
热议问题