Loop Challenge: Reverse List

Hi all,

I am playing around with the codes, and I am wondering why the two sets of codes don’t yield the same result:

#Correct code
def reversed_list(lst1, lst2):
  for index in range(len(lst1)):
    if lst1[index] != lst2[len(lst2) - 1 - index]:
      return False
  return True
#Uncomment the lines below when your function is done
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))

result is correct as output is
True
False

#Incorrect code
def reversed_list(lst1, lst2):
  for index in range(len(lst1)):
    if lst1[index] == lst2[len(lst2) - 1 - index]:
      return True
  return False
#Uncomment the lines below when your function is done
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))

This result is incorrect as the output is
True
True

I am wondering how does [1, 5, 3], [3, 2, 1] pass through the if and somehow satisfy the condition

I think what you are missing here is that once your code gets to a return statement, it will not continue with your for loop. It will return whatever you tell it to and that’s the end of it.

So, in the “incorrect” version of the code, your conditional statement checks if lst1[0] is equal to lst2[2], it determines it is true, goes to the body of your if and finds the return statement. It will never check the rest of the indices.

4 Likes

Thanks for the explanation! I think I conceptually get it. But it’ll take me a while from knowing there is an issue with my code to actually fix it and get it to work as intended :smiley:

You need to reverse your logic. Rather than checking if the numbers are the same inside the loop to then return True, check if they are not the same to return False. That way, every iteration of the loop will carry on as long as you don’t find a difference. And if the loop finishes all the items in the list, then your last statement in the function, after the loop, could return True because you already checked all positions and none of them triggered your conditional.

Let me know if you are having issues wrapping your head around it and I’ll draw a flow chart! :+1: