Function Arguments
Use the full potential of Python function arguments! Learn about the different ways to work with the Python unpacking operator.
StartKey Concepts
Review core concepts you need to learn to master this subject
Mutable Default Arguments
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.
- 1In 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 …
- 2To 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…
- 3Now 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 …
- 4Python 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…
- 5Working 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…
- 6So 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 …
- 7Hopefully, 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 …
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory