Hi all, I have a quick question on the answer to the Reversed list challenge in the Loops module
https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-loops-cc/exercises/reversed
The challenge is:
Create a function named reversed_list()
that takes two lists of the same size as parameters named lst1
and lst2
.
The function should return True
if lst1
is the same as lst2
reversed. The function should return False
otherwise.
For example, reversed_list([1, 2, 3], [3, 2, 1])
should return True
.
and the correct code for the answer is:
def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2) - 1 - index]:
return False
return True
My question is: why do we just say “return True” at the end, instead of “else return True”?
Thanks!
This is because after the for
loop, if the return False
has not been reached, the return True
will be reached due to the flow of the program. else
is only used if you want something to be run after the if
-but only if the if
is false:
if 1 != 1:
print("1 != 1")
else:
print("1==1")
print("This program has ended")
In the case above, you want This program has ended
to run regardless of the result of the if
condition, but you still want a verdict of whether 1==1
.
Thanks for the response. Following your logic: don’t we want “return True” to run only if the if condition is false?
Yes, but it needs to be out of the loop, otherwise the function will return a value on the first iteration-and that wouldn’t check the whole list-just the first element:
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2) - 1 - index]:
return False
else:
return True
Image passing in these lists:
reversed_list([1, 2, 3], [3, 3, 1])
The first iteration would check to see if the first element of the first list (1
) equals the last element of the second list (2
). Then, since you have the else
within the loop, the function would return True
, even though these lists aren’t the reverse of eachother.