Skip to content

Instantly share code, notes, and snippets.

@rmariano
Last active June 22, 2017 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmariano/7593536 to your computer and use it in GitHub Desktop.
Save rmariano/7593536 to your computer and use it in GitHub Desktop.
Pass default mutable arguments in Python

License

Python - How to pass empty lists as default argument

On this gist I would like to point out an aspect of Python that might present some issues if it is not implemented correctly.

Suppose we have a function and we need to define that some of its parameters take an empty list as a default argument. Something like the following, for example, might be a typical implementation:

    def process_list(a, b=[]):
        b.extend(a)
        print(b)

Here the first line with b=[] presents a problem. Under this definition, if we run the following:

    process_list([1,2,3])
    process_list([4,5], [0])
    process_list([7,8,9])

This is what you get, compared to what you would expect.

Expected Obtained
[1, 2, 3] [1, 2, 3]
[0, 4, 5] [0, 4, 5]
[7, 8, 9] [1,2,3,7,8,9]

The problem is that the second time that you try to use b (on the third function call), Python has already defined it, so it will keep the value that had the first time it was declared (when it parsed the function definition).

To avoid this, you should give the parameter a different value (usually called sentinel, and assign the default value manually, for example:

    def process_list(a, b=None):
        b = b or []
        b.extend(a)
        print(b)

This time, it will work properly.

To sum up, please bear in mind this when defining a function of this kind in Python, and also take into consideration that the same applies not only for lists but for sets, or dictionaries as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment