Lists and Loops return

Hey guys!

i am dealing with this exercise and need some help:
https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-loops-cc/exercises/reversed

my answer was:
def reversed_list(lst1, lst2):
for i in range(len(lst1)):
if lst1[i] == lst2[len(lst1)-1-i]:
return True
return False

the correct answer would be:
def reversed_list(lst1, lst2):
for i in range(len(lst1)):
if lst1[i] != lst2[len(lst1)-1-i]:
return False
return True

Why is my answer incorrect? They seem both identical for me, but python reads every statement as true every time i run my answer…

Cheers!

Hi @feibes!
Can you please format your code like the following guide shows?

2 Likes
def reversed_list(lst1, lst2):
    for i in range(len(lst1)):
        if lst1[i] != lst2[len(lst1)-1-i]:
            return False
    return True
```
1 Like

sorry! that would be my answer, that seems to be wrong…
Thanks!

2 Likes

Hello @feibes! Welcome to the Codecademy forum!

Looking at your answer, if the first two elements compared are equal the remaining elements of each list will never be checked. What does the return statement do?

3 Likes

thanks! idk if i got it right though… i thought the loop would run until len(lst1) is reached… does the True statement work like a break and thats why i have to try the false first?

cheers!

2 Likes

return ends the execution of a function (EVERY function EVERY time) it is executed. When your first comparison evaluates to True, your code returns True to the line of code that called the function, so the remaining elements are not iterated through at all. You never want a return statement to be reached until the function has completed the task assigned to it. You could check the equality of the elements rather than the inequality if you really wanted to, but it would require a few more lines of code, and changing the return values around:

def reversed_list(lst1, lst2):
    for i in range(len(lst1)):
        if lst1[i] == lst2[len(lst1)-1-i]:
            continue # if they're equal do nothing
        else:
            return False # if they're not equal return False (this ends the function)
    return True # if we get this far, the entire lists have been compared, and we haven't returned False, so we can safely return True
    

As you can see, comparing the inequality as the solution suggested makes the code more concise, and perhaps easier to follow.
Don’t feel bad. Many, many new coders are confused by what exactly return does. Hope this helps!
Happy coding!!

4 Likes