Reversed list

Hey. Could someone explain to me why this function isn’t working.

Its from the exercise

"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."

it works with:

if lst1[index] != lst2 [len(lst2-1-index]:
   return False  

return True

But doesn’t work the other way. Why so?

Hey there and welcome to the forums :slight_smile:

Might wanna look at the logic within your loop here, currently you say that if a condition is True than immediately return True. All this states is that the first elements to be compared are the same, What about the other elements in the list?

I’m assuming there was a typo here and you meant to have a parenthesis here:

if lst1[index] != lst2 [len(lst2)-1-index]:
                                ^
   return False  

This works because you only need one wrong pair to know the list isn’t reversed, the rest won’t matter.

2 Likes

If you wanted to finish with your original approach, this would have done it:

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

print(reversed_list([1,2,3], [3,2,1]))
print(reversed_list([1,5,3], [3,2,1]))

continue allows it to finish the iterations of the for loop.