Need help on inner functions


Could someone explain to me why my_list is passed to function get_last_item instead of list in the outer function?

Correct code:

def pop(list):  
    def get_last_item(my_list):   
        return my_list[len(list) - 1] 

    return list

My code:

def pop(list):  
    def get_last_item(list):   
        return list[len(list) - 1] 

    return list

Hi @Rucha,

Thanks for swift reply.

It makes sense to make that a list is passed to the pop function.

Next the inner function get_last_item accepts one argument: my_list. How does get_last_item know what arguments are passed to it?

I am a little confused :frowning:

hey @LuukvanVliet

Apologies for confusing you. Please ignore the previous post. :slightly_frowning_face:

Please consider the below code as an example:


inner_list (or my_list) is not a separate list. It is an argument to be passed to get_last_item function.

this value is passed to the function by this code getting_last_item(outer_list) as highlighted/ shaded.

The first cell works on the passed argument (indirectly outer_list) of the inner function.

The second cell which reflects the solution is working on the argument passed to the outer function itself. So it’s basically an example of utilizing arguments of parent level function by the child level function.

Hope this helps. Let me know if you still have doubts. You are helping me learn too!

1 Like

Hi @Rucha,

This clarifies a lot!

Can I call inner_list a variable in the nonlocal scope?

Is inner_list defined/created by creating function get_last_item(inner_list)

Or is inner_list defined/created by returning inner_list[len(outer_list) -1]

Hi @LuukvanVliet

We can call inner_list a parameter since it’s declared within parenthesis while creating function or an argument when the function will be called and value will be passed to it.

we are parameterizing the function - basically telling it you can’t be called empty unless the default value was supplied to the parameter like as below:

def get_function(inner_list = ["a", "default", "list"]): 
      # some code

In the last part, we are manipulating the supplied argument.

1 Like

Thanks @Rucha.

I did a few exercises and I believe I understand it :slight_smile:

1 Like