Print a list in reverse order with range()?

前端 未结 19 696
长发绾君心
长发绾君心 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).

    0 讨论(0)
  • 2020-11-30 17:39

    No sense to use reverse because the range method can return reversed list.

    When you have iteration over n items and want to replace order of list returned by range(start, stop, step) you have to use third parameter of range which identifies step and set it to -1, other parameters shall be adjusted accordingly:

    1. Provide stop parameter as -1(it's previous value of stop - 1, stop was equal to 0).
    2. As start parameter use n-1.

    So equivalent of range(n) in reverse order would be:

    n = 10
    print range(n-1,-1,-1) 
    #[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    
    0 讨论(0)
  • 2020-11-30 17:40
    range(9,-1,-1)
        [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    

    Is the correct form. If you use

    reversed(range(10))
    

    you wont get a 0 case. For instance, say your 10 isn't a magic number and a variable you're using to lookup start from reverse. If your n case is 0, reversed(range(0)) will not execute which is wrong if you by chance have a single object in the zero index.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 17:42
    for i in range(8, 0, -1)
    

    will solve this problem. It will output 8 to 1, and -1 means a reversed list

    0 讨论(0)
  • 2020-11-30 17:42
    [9-i for i in range(10)]
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    
    0 讨论(0)
提交回复
热议问题