Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a list?

Tags:

python

list

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.

like image 694
Leo.peis Avatar asked Oct 15 '10 06:10

Leo.peis


People also ask

How can you reverse a list in Python?

In Python, there is a built-in function called reverse() that is used to reverse the list. This is a simple and quick way to reverse a list that requires little memory. Syntax- list_name. reverse() Here, list_name means you have to write the name of the list which has to be reversed.

How do you reverse a list in slicing?

To reverse a list in Python, you can use negative slicing: As you want to slice the whole list, you can omit the start and stop values altogether. To reverse the slicing, specify a negative step value. As you want to include each value in the reversed list, the step size should be -1.


1 Answers

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

like image 175
codaddict Avatar answered Oct 03 '22 07:10

codaddict