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.
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.
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:-
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.
The most direct translation of your requirement into Python is this
for
statement:This is rather cryptic but may be useful.
You can make use of the
reversed
function for this as:Note that
reversed(...)
does not return a list. You can get a reversed list usinglist(reversed(array))
.