Code Challenges Loops (Advanced) Computer Science Qn 5 help

Hi. I’m currently stuck on a question as follows:

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 my code was

def reversed_list(lst1, lst2):
  for index in range(len(lst1)):
    if lst1[index] == 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]))

and it returned True for both statements. My guess is that it only compared the 0 index of the first list and the -1 index of the second list, matched it up to be true, then the for loop is broken from there. Anyone can guide me to the modification required to make the code iterate through the whole list before breaking the loop? I found myself in a lot of problems being stuck on this issue. Thanks!

1 Like

Seems you already pretty close to the solution? :slight_smile:

you realize what causes the loop to break, so you only want to return True outside/after the loop

we can return False when the values do not equal, this will also break the loop, but that is fine, because once values do not match, we know we don’t have reversed lists

1 Like

Hi! Thanks so much for your reply. I kinda get where you’re coming from but i’m still a little confused. If I write

    if lst1[index] != lst2[-1 - index]:
      return False
    else:
      return True

instead, wouldn’t the code still check for the 0th for the first list and -1th index for the second list only, then return a True regardless of the rest of the list? Sorry, i’m very fresh to coding and can’t quite wrap my head around loops :frowning:

yes, so return True still needs to be moved outside/after the loop

2 Likes