Key Concepts

Review core concepts you need to learn to master this subject

Mutable Default Arguments

# Here, an empty list is used as a default argument of the function. def append(number, number_list=[]): number_list.append(number) print(number_list) return number_list # Below are 3 calls to the `append` function and their expected and actual outputs: append(5) # expecting: [5], actual: [5] append(7) # expecting: [7], actual: [5, 7] append(2) # expecting: [2], actual: [5, 7, 2]

Python’s default arguments are evaluated only once when the function is defined, not each time the function is called. This means that if a mutable default argument is used and is mutated, it is mutated for all future calls to the function as well. This leads to buggy behaviour as the programmer expects the default value of that argument in each function call.

Function Arguments
Lesson 1 of 1
  1. 1
    In Python, there are three common types of function arguments: - Positional arguments: arguments that are called by their position in the function definition. - Keyword arguments: arguments that …
  2. 2
    To start exploring variable argument lengths in Python functions, let’s take a look at a familiar function we have been using for a long time: print(‘This’, ‘is’, ‘the’, ‘print’, ‘function’) No…
  3. 3
    Now that we have seen the basics of working with positional argument unpacking let’s examine how to use it in a more meaningful way. Say we wanted to build a function that works similarly to our …
  4. 4
    Python doesn’t stop at allowing us to accept unlimited positional arguments; it also gives us the power to define functions with unlimited keyword arguments. The syntax is very similar but uses two…
  5. 5
    Working with *kwargs looks very similar to its *args counterpart. Since * generates a standard dictionary, we can use iteration just like we did earlier by taking advantage of the .values() metho…
  6. 6
    So far we have seen how both args and *kwargs can be combined with standard arguments. This is useful, but in some cases, we may want to use all three types together! Thankfully Python allows us …
  7. 7
    Hopefully, by now, we have started to see the power of using the * and ** operators in our function definitions. However, Python doesn’t stop there! Not only can we use the operators when defining …
  8. 8
    We covered a lot of ground in this lesson! We learned all about how functions can accept different arguments and different styles in which we can pass those arguments in. We learned: * How to pack…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo