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
With reversed and list:
>>> list1 = [1,2,3]
>>> reversed_list = list(reversed(list1))
>>> reversed_list
>>> [3, 2, 1]
Strictly speaking, the question is not how to return a list in reverse but rather how to reverse a list with an example list name array
.
To reverse a list named "array"
use array.reverse()
.
The incredibly useful slice method as described can also be used to reverse a list in place by defining the list as a sliced modification of itself using array = array[::-1]
.
Reversing in-place by switching references of opposite indices:
>>> l = [1,2,3,4,5,6,7]
>>> for i in range(len(l)//2):
... l[i], l[-1-i] = l[-1-i], l[i]
...
>>> l
[7, 6, 5, 4, 3, 2, 1]
For reversing the same list use:
array.reverse()
To assign reversed list into some other list use:
newArray = array[::-1]
You can also use the bitwise complement of the array index to step through the array in reverse:
>>> array = [0, 10, 20, 40]
>>> [array[~i] for i, _ in enumerate(array)]
[40, 20, 10, 0]
Whatever you do, don't do it this way ;)
list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
j=i-l
l-=1
rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data