How can I reverse a list in Python?

后端 未结 30 2420
既然无缘
既然无缘 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:31

    You could always treat the list like a stack just popping the elements off the top of the stack from the back end of the list. That way you take advantage of first in last out characteristics of a stack. Of course you are consuming the 1st array. I do like this method in that it's pretty intuitive in that you see one list being consumed from the back end while the other is being built from the front end.

    >>> l = [1,2,3,4,5,6]; nl=[]
    >>> while l:
            nl.append(l.pop())  
    >>> print nl
    [6, 5, 4, 3, 2, 1]
    

提交回复
热议问题