Confused on Loops

I am currently struggling with this code challenge.

I am confused as to why this answer returns two True statements:

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

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

While (what I think is) the opposite of the function returns the correct answer of one True and one False statement:

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

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

Can somebody explain to me what part of the code makes this the case, as in what causes the second True statement to be returned in the first code, and what causes the False statement to be returned in the second code?

Thank you!

If we take the first iteration then we first meet an if statement. Should the condition evaluate to True then the function would return True and exit. That condition appears to be indexing the first item in lst1 and the last item in lst2. This would be an issue for the sake of the code challenge because you’ve already returned from the function even if only the first element in lst1 and the last element in lst2 match. That is not the entire list.

Consider how this works for arguments [1, 2, 3], [3, 2, 1]. There are only 3 elements so this is easy to follow with pen and paper.

Your second option uses not equivalent to. Do the same thing step by step for each of the three (or less) iterations. So as for what causes the differences it’s because == and != are operators that do opposite comparisons.

1 Like