Confused about indentation for return


#1



Hello everyone!

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096

def purify(l):
    p = []
    for x in l:
        if x % 2 == 0:
            p.append(x)
    return p

The above code gave me the right answer, whereas when I first did it I indented return under the if(see code below).

def purify(l):
    p = []
    for x in l:
        if x % 2 == 0:
            p.append(x)
        return p

With return indented more, it gives the error "Oops, try again. Your function fails on purify([4, 5, 5, 4]). It returns [4] when it should return [4, 4]."

Every time I have to test it out but is there an explanation to where the return should be?

<What do you expect to happen instead?>


<do not remove the three backticks below>
```python



#2

Hi @oliviajcheng,

The essence of the issue is to decide when you want the return statement to execute. In the first example, it is outside the loop, so the loop completes all its iterations prior to execution of the return statement. All items in l get processed.

In the second example, it is part of the loop due to its degree of indentation, and it executes during the first iteration of the loop. This terminates execution of the function. As a result, only the first item in l gets processed.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.