Print a list in reverse order with range()?

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

    For those who are interested in the "efficiency" of the options collected so far...

    Jaime RGP's answer led me to restart my computer after timing the somewhat "challenging" solution of Jason literally following my own suggestion (via comment). To spare the curious of you the downtime, I present here my results (worst-first):

    Jason's answer (maybe just an excursion into the power of list comprehension):

    $ python -m timeit "[9-i for i in range(10)]"
    1000000 loops, best of 3: 1.54 usec per loop
    

    martineau's answer (readable if you are familiar with the extended slices syntax):

    $ python -m timeit "range(10)[::-1]"
    1000000 loops, best of 3: 0.743 usec per loop
    

    Michał Šrajer's answer (the accepted one, very readable):

    $ python -m timeit "reversed(range(10))"
    1000000 loops, best of 3: 0.538 usec per loop
    

    bene's answer (the very first, but very sketchy at that time):

    $ python -m timeit "range(9,-1,-1)"
    1000000 loops, best of 3: 0.401 usec per loop
    

    The last option is easy to remember using the range(n-1,-1,-1) notation by Val Neekman.

提交回复
热议问题