How can I reverse a list in Python?

Leo.peis picture Leo.peis · Oct 15, 2010 · Viewed 1.6M times · Source

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 an array, but from the end to the beginning.

Answer

codaddict picture codaddict · Oct 15, 2010

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)).