# Python Code Challenges: Loops (Advanced) Exercise 5

Hello,

I’m working on the Loops (Advanced) Exercise 5: Reversed List.

Why does the solution provided work?
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]))

But this code does not work?
def reversed_list(lst1, lst2):
for vals in range(len(lst1)):
if lst1[vals] == lst2[len(lst2) - 1 - vals]:
return True
return False

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

The solution returns (as expected):
True
False

But the latter returns:
True
True

Can you please post the code showing the indentation you currently have?

Hi,
In the first loop, we’re checking if the values are the same. If they are not, we know it’s false so we don’t need to check anymore so we can return from the function with false.
If they’re the same the loop will continue until we’ve checked everything, then ultimately, return true at the end.

In the second, the check returns true if it finds the respective elements are the same. This means once the first pair are checked - the 1’s - the function will return true without checking the rest of the arrays.

Hope that helps

1 Like