Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does return True have to be outside the if statement and the for loop?

Tags:

python

I'm trying to see if lst2 is the reverse of lst1.

For the following code, why does return True have to be outside the if statement. When I put else: return False with the if statement, both of the prints return True (which is incorrect). Thank you!

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


print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))
like image 531
Khoi Nguyen Avatar asked Feb 02 '26 03:02

Khoi Nguyen


1 Answers

If you put it into the if, i.e. into the same conditionality as the return False, but after it, then it will never be executed, because the function will always have been left with the first return. Or it will always be executed inside the if, before, leaving it and thereby unintendedly overriding the intended False. This seems is what you are observing.

If you put it into the loop (but outside the if) it will be executed during the first iteration of the loop, i.e. much too early.

If you put it into the loop, but with an else, it will still be executed too early. at the first case of not False. This is still not what you want, because you only want a True when there is no False anywhere in the loop, not already at the first case of not False.

You only want to return a true boolean if the loop gets completly through without ever triggering the False. You want that because otherwise you might miss cases of False.

This is why the position you describe and use in the shown code, outside of both, the if and the loop, is the only correct way.

like image 78
Yunnosch Avatar answered Feb 03 '26 17:02

Yunnosch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!