How can I reverse a list in Python?

后端 未结 30 2617
既然无缘
既然无缘 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条回答
  •  -上瘾入骨i
    2020-11-21 23:31

    If you want to store the elements of reversed list in some other variable, then you can use revArray = array[::-1] or revArray = list(reversed(array)).

    But the first variant is slightly faster:

    z = range(1000000)
    startTimeTic = time.time()
    y = z[::-1]
    print("Time: %s s" % (time.time() - startTimeTic))
    
    f = range(1000000)
    startTimeTic = time.time()
    g = list(reversed(f))
    print("Time: %s s" % (time.time() - startTimeTic))
    

    Output:

    Time: 0.00489711761475 s
    Time: 0.00609302520752 s
    

提交回复
热议问题