FAQ: Code Challenge: Loops - Reversed List

When a return is executed, the value following return is handed back to the caller, along with the control flow. return exits not just the loop, but also the function. Doesn’t matter what the value returned is, the function is exited. With this problem, once two values are compared that are not equal, it is safe to exit the function, and return False, but you cannot exit the function, and return True until after you have finished comparing all of the elements of the lists. Imagine you are going through a bag of apples, and discarding the rotten ones. You grab an apple, and the first side you see has a big, black, mushy spot, so you throw it out. The next one looks okay at first glance. Can you assume the apple is okay before you inspect the rest of it?

1 Like

I thought I 'd jus share my solution. This one was pretty mind boggling, the hint from the exercise helped. First I made an empty list that got appended by the reversed list2. That worked, but I don’t think that was what the exercise was about. Then I made this. If I can create an empty list to start with, I might as well start off with a boolean:

Why does the below function not work ?

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

Did you read the replies in this topic? Scrolling through the replies, i see i answered the exact same question:

and so did ionatan:

and there might be even more. Always check existing replies first :wink: maybe the answer you need is already there

Thank you very much.

Question: How is “Return” used, or how is “return” being justified by Python?

def reversed_list(lst1,lst2):
  index = list(range(0,len(lst2)))
  lst2r=[]
  for i in index:
    lst2r.append(lst2[len(lst2)-1-i])
  *return lst2r*   
  if lst1 == lst2r:
    return True
  else:
    return False

I added a “return lst2r” in the middle of the code to check if I got the correct output for the reversed list. However, when I tried to run this code, it seems it never goes down into the if statement under the “return lst2r” and the output was just the reversed list. Why my code is not returning true or false? They are at same indentation and they should run, aren’t they? Thanks.

return is literally returning/handing back data to caller, signaling the function is done executing.

if you want to inspect your code, use print()