How can I reverse a list in Python?

后端 未结 30 2609
既然无缘
既然无缘 2020-11-21 22:32

How can I do the following in Python?

array = [0, 10, 20, 40]
for (i = array.length() - 1; i >= 0; i--)

I need to have the elements of a

30条回答
  •  长发绾君心
    2020-11-21 23:27

    I find (contrary to some other suggestions) that l.reverse() is by far the fastest way to reverse a long list in Python 3 and 2. I'd be interested to know if others can replicate these timings.

    l[::-1] is probably slower because it copies the list prior to reversing it. Adding the list() call around the iterator made by reversed(l) must add some overhead. Of course if you want a copy of the list or an iterator then use those respective methods, but if you want to just reverse the list then l.reverse() seems to be the fastest way.

    Functions

    def rev_list1(l):
        return l[::-1]
    
    def rev_list2(l):
        return list(reversed(l))
    
    def rev_list3(l):
        l.reverse()
        return l
    

    List

    l = list(range(1000000))
    

    Python 3.5 timings

    timeit(lambda: rev_list1(l), number=1000)
    # 6.48
    timeit(lambda: rev_list2(l), number=1000)
    # 7.13
    timeit(lambda: rev_list3(l), number=1000)
    # 0.44
    

    Python 2.7 timings

    timeit(lambda: rev_list1(l), number=1000)
    # 6.76
    timeit(lambda: rev_list2(l), number=1000)
    # 9.18
    timeit(lambda: rev_list3(l), number=1000)
    # 0.46
    

提交回复
热议问题