Reversed List Code Challenge Comparison

Hi again,
I was going through the rest of the code challenges and found the reverse loop to be quite challenging. However, getting past the actual logic behind the iteration. The one aspect of this that I am still confused about is the comparison we are making. I have searched the forums and have come to a better understanding of how return works, but I can’t seem to figure out what is happening here.

#Write your function here def reversed_list(lst1,lst2): for i in range(len(lst1)): if lst1[i] != lst2[len(lst2)-1 - i]: return False else: return True #Uncomment the lines below when your function is done print(reversed_list([1, 2, 3], [3, 2, 1])) print(reversed_list([1, 5, 3], [3, 2, 1]))

If I were to change the comparison operator to “==”. The function will no longer be accurate. From what I understand by reading the forum, this is because it is acting as a false positive and not checking the entirety of the list. Instead, it’s hitting the return once and returning true.

The most obvious thing I can’t seem to wrap my head around is if I change lst2’s last element to be different than lst1’s first. It’s still returning true. I don’t really understand what is happening.

Lets say this is our code:

#Write your function here
def reversed_list(lst1,lst2):


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

  
#Uncomment the lines below when your function is done
print(reversed_list([1, 2, 3], [3, 2, 7]))

so then the first item of list1 (1) is compared with the last item of list2 (7), which is false. No return keyword reached, so the loops continues.

then the middle items are compared, those are equal, so True is returned.

so this code would “work” if none of the items in the lists matches. I can highly recommend to step through your code in a tool like this one:

Python Tutor - Visualize Python, Java, JavaScript, C, C++, Ruby code execution

2 Likes

Ohhh, ok. Yeah this actually makes sense now. Thank you for the visualization website as well!

Yes, and the trick is to teach yourself to be able to walk/step through the program, either with a tool/debugger or in your mind :slight_smile:

Like you can see, I added a print() statement to your code to visualize the code execution

1 Like