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
You could always treat the list like a stack just popping the elements off the top of the stack from the back end of the list. That way you take advantage of first in last out characteristics of a stack. Of course you are consuming the 1st array. I do like this method in that it's pretty intuitive in that you see one list being consumed from the back end while the other is being built from the front end.
>>> l = [1,2,3,4,5,6]; nl=[]
>>> while l:
nl.append(l.pop())
>>> print nl
[6, 5, 4, 3, 2, 1]
There are 3 methods to get the reversed list:
Slicing Method 1: reversed_array = array[-1::-1]
Slicing Method 2:
reversed_array2 = array[::-1]
Using the builtin function: reversed_array = array.reverse()
The third function actually reversed the list object in place. That means no copy of pristine data is maintained. This is a good approach if you don't want to maintain the old version. But doesn't seem to be a solution if you do want the pristine and reversed version.
def reverse(text):
output = []
for i in range(len(text)-1, -1, -1):
output.append(text[i])
return output
array=[0,10,20,40]
for e in reversed(array):
print e
Use list comprehension:
[array[n] for n in range(len(array)-1, -1, -1)]
Using reversed(array) would be the likely best route.
>>> array = [1,2,3,4]
>>> for item in reversed(array):
>>> print item
Should you need to understand how could implement this without using the built in reversed
.
def reverse(a):
midpoint = len(a)/2
for item in a[:midpoint]:
otherside = (len(a) - a.index(item)) - 1
temp = a[otherside]
a[otherside] = a[a.index(item)]
a[a.index(item)] = temp
return a
This should take O(N) time.