How is this program not working properly? -Reversed List

This is from Python Loop Challenges.

The logic I copy below for the question 5 looks ok to me but it is not giving me the desired output which is True and False

def reversed_list(lst1, lst2): for index in range(len(lst1)): if lst1[index] == lst2[-index-1]: 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]))

The way you have it now, if the first thing in lst1 is the same as the last thing in lst2,
then the function returns True, and no other indices are checked. (The loop would stop after 1 iteration in that case).

You want to the loop to keep going unless the stuff is not the same,
so you should be checking whether the stuff at those indices are not the same.

def reversed_list(lst1, lst2):
  for index in range(len(lst1)):
    if lst1[index] != lst2[-index-1]:
      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]))

Thanks for the reply, @janbazant1107978602. But I don’t get it. I have a for loop there why would it stop once we have True why it’s not going to run the else condition?

Also, your code gives True True as well as opposed to the desired outcome.

hi,
The problem you’re having is that your loop checks the first character of lst1 with the last of lst2 and when they match it exits the function and returns True. It’s not checking the rest of the lists.

What @janbazant1107978602 has done is flip the check round ( I suspect you missed the != instead of == in the if statement ).
This means it will keep comparing each char in turn until it either finds one that is wrong ( and exits with False ) or gets to the end, and it’s True.

Hope that helps.

The function (and the loop) stop once it reaches a return.
So, for

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

on the first iteration of the loop,
if the first thing in lst1 is the same as the last thing in lst2,
it does return True ,
which ends the function (and the loop).

Thanks @janbazant1107978602 and @pluginmaybe, the logic looks straightforward after some thinking. the only thing i want to make sure i got it right: Does the return True stops for loops all the time?

yes, return stops the loop (if the loop is inside a function)