Print a list in reverse order with range()?

前端 未结 19 693
长发绾君心
长发绾君心 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条回答
  •  -上瘾入骨i
    2020-11-30 17:38

    Very often asked question is whether range(9, -1, -1) better than reversed(range(10)) in Python 3? People who have worked in other languages with iterators immediately tend to think that reversed() must cache all values and then return in reverse order. Thing is that Python's reversed() operator doesn't work if the object is just an iterator. The object must have one of below two for reversed() to work:

    1. Either support len() and integer indexes via []
    2. Or have __reversed__() method implemented.

    If you try to use reversed() on object that has none of above then you will get:

    >>> [reversed((x for x in range(10)))]
    TypeError: 'generator' object is not reversible
    

    So in short, Python's reversed() is only meant on array like objects and so it should have same performance as forward iteration.

    But what about range()? Isn't that a generator? In Python 3 it is generator but wrapped in a class that implements both of above. So range(100000) doesn't take up lot of memory but it still supports efficient indexing and reversing.

    So in summary, you can use reversed(range(10)) without any hit on performance.

提交回复
热议问题