Reversed List - https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-python-loops/lessons/python-functions-loops-cc/exercises/reversed

Why does this not work:

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

while this does:

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]))

Please help me out. I’m quite confused. Thank You!

the first code snippet compares the first value of lst1 with the last value of lst2, based on this comparison determine if the lists are reversed of each other

the second code snippet will return false when values don’t math (so lists aren’t reversed of each other), when it runs out of values to compare (without return false, which would end the function), True is returned (and rightfully so)

2 Likes

You can use this code

if lst1[i] == lst2[::-1]:

based on this statement

a[start:stop:step] # start through not past stop, by step

for more details, you can check this link

1 Like