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.
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.
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.
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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With