Last Updated: Sunday 24th March 2013

Virtually every programming language has functions and procedures, a way of separating out a block of code that can be called many times from different places in your program, and a way to pass parameters into them. Python is no different, so we'll quickly run over the standard stuff that most languages have, then take a look at some of the cool stuff Python has to offer.

Positional Function Parameters in Python

Here's a really simply function:

When used, we get the following:

This function has 3 positional parameters (each one gets the next value passed to the function when it is called – val1 gets the first value (1), val2 gets the second value (2), etc).

Named Python Functional Parameters (with defaults)

Python also supports named parameters, so that when a function is called, parameters can be explicitly assigned a value by name. These are often used to implement default, or optional, values. For example:

Using the function gives us the following:

In this example, calcSum is optional - if it's not specified when you call the function, it gets a default value of True.

Potential Python Function Parameter Problems

One thing to keep in mind is that default values are evaluated when the function is compiled, which is an important distinction if the value is mutable. The behaviour below is probably not what was intended:

When using the function:

This happens because the default value (an empty list) was evaluated once, when the function was compiled, then re-used on every call to the function. To get an empty list on every call, the code needs to be written like this:

When using the function, we get:

Python Function Parameter Order

Unlike positional parameters, it doesn't matter what order named parameters are specified in:

When used, we get the following:

Unusually, Python also allows positional parameters to be specified by name:

When used, we get the following:

Here's a more complex example:

When used, we get the following:

This seems really confusing, but the key to understanding how it works is to recognize that the function's parameter list is a dictionary (a set of key/value pairs). Python matches up the positional parameters first, then assigns any named parameters specified in the function call.

Variable Python Function Parameter Lists

The Python coolness really kicks in when you start to look at variable parameter lists. You can write your functions without even knowing what parameters will be passed in!

In the function below, the asterisk in front of the vals parameter means any other positional parameters.

When using the function, we get:

The first positional value we specify in the function call (10) is given to the first parameter in the function (cutoffVal), then all the remaining positional values are put in a tuple and assigned to vals. We then iterate through these values, looking for any that are less than the cutoff value.

We can also do the same kind of thing with named parameters. A double asterisk in front of the dict parameter below means any other named parameters. This time, Python will give them to us as key/value pairs in a dictionary.

When using the function, we get:

Note in the last example that the values are not printed out in the same order that they were specified in the function call. This is because these extra named parameters are passed through in a dictionary, which is an un-ordered data structure.

A Real World Example

So, what would you use all this for? As an example, it's common for programs to generate messages from a template that has placeholders for values that will be inserted at run-time. For example:

Hello {name}. Your account balance is {1}, you have {2} available credit.

The function below takes such a template and a set of parameters that will be used to replace the placeholders.

Here it is in action:

To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.

  • Carl Smith

    Nice article. You covered it really well.

    One thing I learnt the other day is that you can pass arguments to be unpacked using the same syntax.

    def f(a, b):
    print a + b

    a = (1, 2)


    You can do this with dicts as well.

  • budyk

    Simple n Clean for beginners

  • josephat

    how can one specify a parameter in python that takes a specific data structure

    • You can use typehinting (doc) as part of the language and/or documenting function parameters in the docstring. There’s various conventions out there, you might want to checkout Google’s Python Style Guide’s (example) and PEP 0257 — Docstring Conventions.

      • josephat

        Thanks Jackson… I have been trying to ask myself what is the essence of learning searching and sorting algorithms in computer science while one can use the built ins functions e.g when you want to sort a list…u can use sorted() function…please help me understand the bigger picture

        • Practically speaking, the importance of knowledge on sorting algorithms and other low-level CS concepts depends on what level of the stack you work on. If you’re developing a software/core Python library, kernel module, custom C++ library, then you would want to know exactly what best sorting method to use and why, in each use-case. However say you’re writing a script to email a text file with sorted data, just use sorted() and be done with it. High level languages and libraries let us to a large degree remove (abstract) that layer of low-level complexity. Hope that makes some sort of sense 🙂

          • josephat

            OK THANKS SO MUCH

  • Pingback: Python Decorators: A Deep Dive - TLDLife()