Print a list in reverse order with range()?

前端 未结 19 757
长发绾君心
长发绾君心 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:39

    Use the 'range' built-in function. The signature is range(start, stop, step). This produces a sequence that yields numbers, starting with start, and ending if stop has been reached, excluding stop.

    >>> range(9,-1,-1)   
        [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    >>> range(-2, 6, 2)
        [-2, 0, 2, 4]
    

    In Python 3, this produces a non-list range object, which functions effectively like a read-only list (but uses way less memory, particularly for large ranges).

提交回复
热议问题