Check whether a list is the reverse of another #codechallenge

https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-101/modules/cspath-code-challenges/articles/advanced-python-code-challenges-loops

5. Reversed List

Hi everyone,

this one asks to check whether a list is the reverse of another list. My codes goes:

def reversed_list(lst1, lst2):
for i in range(len(lst1)):
if lst1[i] != lst2[- 1 - i]:
return False
else:
return True

This code makes more sense to me than the answer, which is:

def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2) - 1 - index]:
return False
return True

But my code would not work. It would only return True even if it should be false. I am so confused.

and also…
def reversed_list(lst1, lst2):
for i in range(len(lst1)):
if lst1[i] != lst2[- 1 - i]:
return False
return True

this one works, but

def reversed_list(lst1, lst2):
for i in range(len(lst1)):
if lst1[i] == lst2[- 1 - i]:
return True
return False

this one would not work. I am having a really hard time comprehending this

The return True should not be inside the loop,
because if then the loop would always end after checking just the first element, it would never ho to the next iteration because it would reach a return.
You want the loop to continue if the first element worked (meaning the first was the same as the last element)
to check that the next element of the list so you can’t have a return there.

You could have a return True outside the loop
because we’d know that the loop only gets completed if each element in the list worked.

1 Like

Thank you very much! that helped a lot.