How can I reverse a list in python?

How can I do this in python?

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

I need to have the elements of an array but from the end to the beginning.


You can make use of the reversed function for this as:

>>> array=[0,10,20,40]
>>> for i in reversed(array):
...     print(i)

Note that reversed(...) does not return a list. You can get a reversed list using list(reversed(array)) .


>>> L = [0,10,20,40]
>>> L[::-1]
[40, 20, 10, 0]

Extended slice syntax is explained well in the Python What's new Entry for release 2.3.5

By special request in a comment this is the most current slice documentation.


>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]

要么

>>> L[::-1]
[40, 20, 10, 0]
链接地址: http://www.djcxy.com/p/57532.html

上一篇: python列出项目并将语言代码转换为名称

下一篇: 我如何在python中反转列表?