0

In doing problems on Leetcode etc it's often required to iterate from the end of the array to the front and I'm used to more traditional programming languages where the for loop is less awkward i.e. for(int i = n; i >= 0; i--) where n is the last index of the array but in Python I find that I'm doing something like this for i in range(n,-1,-1) which looks a bit awkward so I just wanted to know if there was something more elegant. I know that I can reverse the array by doing array[::-1] and then loop as per usual with for range but that's not really what I want to do since it adds computational complexity to the problem.

alee18
  • 45
  • 1
  • 5

2 Answers2

3

Use reversed which doesn't create a new list, but instead creates a a reverse iterator, and allows you to iterate in reverse:

a = [1, 2, 3, 4, 5]

for n in reversed(a):
     print(n)
Mark
  • 90,562
  • 7
  • 108
  • 148
3

Just a comparison of three methods.

array = list(range(100000))
def go_by_index():
    for i in range(len(array)-1,-1,-1):
        array[i]

def revert_array_directly():
    for n in array[::-1]:
        n

def reversed_fn():
    for n in reversed(array):
        n


%timeit go_by_index()
%timeit revert_array_directly()
%timeit reversed_fn()

Outputs

100 loops, best of 3: 4.84 ms per loop
100 loops, best of 3: 2.01 ms per loop
1000 loops, best of 3: 1.49 ms per loop

The time difference is visible, but as you may see, the second and the third option is not that different, especially if the array of interest is of small or medium size.

Kate Melnykova
  • 1,863
  • 1
  • 5
  • 17