Topic reversed Lists

Hi please see the question and answer below for the topic reversed Lists :

Question
strong text

answer:
strong text

I would like to know why this line: if lst1[index] != lst2[len(lst2) - 1 - index]: has us subrtacting - 1 and - index?

Always keep pencil and paper nearby so you can sketch, list and plan.

Say we have seven elements in each list. With the starting index on the left being zero in the loop, how can we compute the corresponding index on the right?

len(lst) == 7  so `n = 7`

i == 0

n - i == 7

but the last index is one less than the length, so,

n - i - 1 == 6

Now increment i,

n - i - 1 == 7 - 1 - 1 == 5

As we keep incrementing i, the corresponding index gets smaller until i reaches the upper bound, at which time the corresponding index reaches zero.

It gets even more fun when we consider negative indices.

[n - i - 1]  =>  [-(i + 1)]
     6       =>      -1
     5       =>      -2
     4       =>      -3
     3       =>      -4
     2       =>      -5
     1       =>      -6
     0       =>      -7

Letting a and b represent lst1 and lst2, respectively,

for i in range(n):
    if a[i] != b[-(i + 1)]: return False

Now consider that since we are not attempting to mutate the list, only iterate it, it follows this should work for any iterable.

def reverse_match(a, b):
    n = len(a)
    if n == len(b):
        for i in range(n):
            if a[i] != b[-(i + 1)]: break
        else:
            return True
    return False

A list,

>>> reverse_match([1,2,3],[3,2,1])
True
>>> reverse_match([1,2,3,4],[3,2,1])
False
>>> reverse_match([],[])
True
>>> reverse_match([1,2,3],[4,2,1])
False
>>> 

a string,

>>> reverse_match('Python!','!nohtyP')
True
>>> reverse_match('','')
True
>>> reverse_match('Python!','?nohtyP')
False
>>> reverse_match('Python!','nohtyP')
False
>>> 

… and so on.

2 Likes