Advanced Python Function

Passing argument to function

It is very important to understand mutable and immutable objects first. There are two types of objects in Python: mutable and immutable.

  • For immutable objects, changing them inside a function will create a new instance and original instances outside the function are not changed. The immutable objects in Python are string, numbers and tuple.
  • For mutable objects, any changes made to the objects inside a function will affect to the instance outside the function. But reassigning instance will not affect instance outside the function. Mutable objects in Python include list, dictionary, class instance.

Let’s take a look at a couple of examples of using mutable and immutable objects to function.

In the first example, a and s are number and string so they are immutable objects. Any changes made to those objects do not affect the instance outside the functiontry_to_change.

In the second example, list1 and list2 are mutable objects. We append 3 to list 1 and the change affect list1 outside of the function. However for list2, we reassign it to another list, the object outside function does not affect.

In Python , trying to differentiate between “pass-by-value” or “pass-by-reference” is misleading. When you assign a variable, it is an assignment of a reference therefore every function call involves passing the values of those references.

Assign function to variable

In python, function name is like variable so it can be assigned to other variable. Then you can call function under that variable name. You can also put variable which assigned to a function into a list and call it later.

Nested function

In Python, you can define a function within a function which is known as nested function. To define a nested function, just use the keyword def and define a function as normal.

A nested function can access local variables within outer function. Those variables are called free variables of the nested function. The function that accesses values from outer local variables is known as closure.

Here is an example of using nested function:

Anonymous Function

Anonymous function is known as lambda expression which is a function with the function body containing a single return expression statement. Python uses the lambda statement to define an anonymous function. The syntax of anonymous function as follows:

Here is an example of anonymous function:

Note that the anonymous function does not include return statement. It always has one statement which value is returned.

Recursive function

A function calls itself inside its function body is known as recursive function. Python supports recursive function with limited depth level.

Here is an example of using recursive technique to develop a function to calculate factorial of a number:

  • Was this tutorial helpful ?
  • YesNo