Python: Code Challenges - Reversed List

Hello All,

I am trying to check a condition that provides a TRUE value for if I have two lists that are reversed from one another, and a FALSE value otherwise.

Here is my code:

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

print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))

When I run the code, both sets of lists are TRUE even though the second set is FALSE given that 3, 2, 1 is not the inverse of 1, 5, 3.

While I understand the answer key provided by Codecademy, why am I wrong here? I thought that the negative index corresponds to the position at the end of the list.

One reason could be the returns inside the loop. That’s never a good sign. The only return in that context would be a False.

1 Like

Your code never executes the else statement because it prematurely exits with the return statement under the if clause. It only checks the first element of boths lists that happens to be the number 1. That’s why you are getting the same result True, you have to check all the elements inside the list, not only one element.

1 Like

Thanks! I think that makes sense!