Print a list in reverse order with range()?

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

    I thought that many (as myself) could be more interested in a common case of traversing an existing list in reversed order instead, as it's stated in the title, rather than just generating indices for such traversal.

    Even though, all the right answers are still perfectly fine for this case, I want to point out that the performance comparison done in Wolf's answer is for generating indices only. So I've made similar benchmark for traversing an existing list in reversed order.

    TL;DR a[::-1] is the fastest.

    Prerequisites:

    a = list(range(10))
    

    Jason's answer:

    %timeit [a[9-i] for i in range(10)]
    1.27 µs ± 61.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    

    martineau's answer:

    %timeit a[::-1]
    135 ns ± 4.07 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    

    Michał Šrajer's answer:

    %timeit list(reversed(a))
    374 ns ± 9.87 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    

    bene's answer:

    %timeit [a[i] for i in range(9, -1, -1)]
    1.09 µs ± 11.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    

    As you see, in this case there's no need to explicitly generate indices, so the fastest method is the one that makes less extra actions.

    NB: I tested in JupyterLab which has handy "magic command" %timeit. It uses standard timeit.timeit under the hood. Tested for Python 3.7.3

提交回复
热议问题