Is this code okay?

I did it like this:

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

Tell me if it’s not ok, please. I dont want toi hit a “Solution” button :smiley:

If a mismatch is found, there is no point in completing the loop. Simply return False from inside the if block. But that aside, your code will work including on the special case the SCT tests for, reversed_list([], []). Did it not pass? What message was given in the footer of the editor?

It passed, even with empty lists
I changed my code like this:

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

That’s better?
Thanks a lot

Does it still pass the empty list test? If so, then yes, it makes more logical sense since the return False is in the loop (and the if statement).

1 Like

Hi Guys,

can anyone else to me why my code (the one directly below) return true for both occasions?

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

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

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

much appreciated for any help

The conditional returns on the first iteration.

There should not be an else clause since it interrupts the loop prematurely.

If you look at the solution, return True is not in loop, but after it. We only want to return False from inside the loop since there is no reason to continue.