How can I reverse a list in Python?
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.
You can make use of the
reversed function for this as:
>>> array=[0,10,20,40] >>> for i in reversed(array): ... print(i)
reversed(...) does not return a list. You can get a reversed list using
Read more... Read less...
>>> L = [0,10,20,40] >>> L.reverse() >>> L [40, 20, 10, 0]
>>> L[::-1] [40, 20, 10, 0]
This is to duplicate the list:
L = [0,10,20,40] p = L[::-1] # Here p will be having reversed list
This is to reverse the list in-place:
L.reverse() # Here L will be reversed in-place (no new list made)
I think that the best way to reverse a list in Python is to do:
a = [1,2,3,4] a = a[::-1] print(a) >>> [4,3,2,1]
The job is done, and now you have a reversed list.
Using slicing, e.g. array = array[::-1], is a neat trick and very Pythonic, but a little obscure for newbies maybe. Using the reverse() method is a good way to go in day to day coding because it is easily readable.
However, if you need to reverse a list in place as in an interview question, you will likely not be able to use built in methods like these. The interviewer will be looking at how you approach the problem rather than the depth of Python knowledge, an algorithmic approach is required. The following example, using a classic swap, might be one way to do it:-
def reverse_in_place(lst): # Declare a function size = len(lst) # Get the length of the sequence hiindex = size - 1 its = size/2 # Number of iterations required for i in xrange(0, its): # i is the low index pointer temp = lst[hiindex] # Perform a classic swap lst[hiindex] = lst[i] lst[i] = temp hiindex -= 1 # Decrement the high index pointer print "Done!" # Now test it!! array = [2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654] print array # Print the original sequence reverse_in_place(array) # Call the function passing the list print array # Print reversed list **The result:** [2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654] Done! [654, 124, 24, 7, 1, 65, 60, 32, 27, 25, 19, 12, 9, 8, 5, 2]
Note that this will not work on Tuples or string sequences, because strings and tuples are immutable, i.e., you cannot write into them to change elements.
For reversing the same list use:
To assign reversed list into some other list use:
newArray = array[::-1]