In this article we will explore *args and **kwards in Python and their use in functions with examples.
Table of Contents
Introduction
In Python programming we often work with functions that we create to make the code more reusable and easier to understand.
If we need to perform a similar operation multiple times, instead of copy pasting the same code, we create a function that we call multiple times with new arguments to perform this operation.
*args and **kwargs allow us to pass a variable number of arguments to a function, therefore extending the reusability of the functions we created.
Note that usage of *args and **kwargs mainly depends on what operations your functions will perform and how flexible they are to accept more arguments as inputs.
*args in Python
Let’s start with understanding what *args really is and how it can be used!
*args is used to pass a variable number of non-keyworded arguments using the following syntax:
def my_func(*args):
#do something
You can use *args when you aren’t sure how many arguments the function will receive every time it’s used.
For example, let’s say you had a function that was adding two numbers and returning their sum:
#Define a function
def add(x, y):
#Add two numbers
result = x+y
#Print the result
print(f'Result: {result}')
and if you were to test this function with sample values:
#Test with sample values
add(3, 5)
you should get:
8
So far the add() function works correctly as it only takes 2 arguments and returns a result.
Now what if you wanted to add 3 numbers together?
You can try using the add() function:
#Test with 3 values
add(3, 5, 9)
but you will get a TypeError:
TypeError: add() takes 2 positional arguments but 3 were given
This happens because when we defined the add() function, we specifically defined it with two arguments x and y, so when the third argument is passed, it should return an error.
But how can we make this function more robust so it will accept more arguments as an input?
This is where *args becomes handy!
Let’s rewrite the add() function to take *args as argument:
#Define a function
def add(*args):
#Initialize result at 0
result = 0
#Iterate over args tuple
for arg in args:
result += arg
#Print the result
print(f'Result: {result}')
*args will allow us to pass a variable number of non-keyword arguments to the add() function. It will be passed as a tuple, meaning we can iterate over it using a for loop.
Let’s now test this function with sample values:
#Test with 3 arguments
add(3, 5, 9)
#Test with 5 arguments
add(3, 5, 9, 11, 15)
and you should get:
Result: 17
Result: 43
Now we made the add() function more reusable by using *args to make it work with a variable number of non-keyword arguments.
**kwargs in Python
Let’s start with understanding what *args really is and how it can be used!
**kwargs is used to pass a variable number of keyworded arguments using the following syntax:
def my_func(**kwargs):
#do something
You can use **kwargs when you aren’t sure how many arguments the function will receive every time it’s used.
Notice that the main difference between *args and **kwargs is that *args allows for a variable number of non-keyworded arguments, where as **kwargs allows for a variable number of keyworded arguments.
For example, let’s say you had a function that was taking two keyword arguments and printing their values:
#Define function
def print_vals(name, age):
#Print first argument
print(f'name: {name}')
#Print second argument
print(f'age: {age}')
and if you were to test this function with sample values:
#Test with sample values
print_vals(name='Mike', age=20)
you should get:
name: Mike
age: 20
So far the print_vals() function works correctly as it only takes 2 arguments and prints them.
Now what if you wanted to print 3 values?
You can try using the print_vals() function:
#Test with 3 values
print_vals(name='Mike', age=20, city='New York')
but you will get a TypeError:
TypeError: print_vals() got an unexpected keyword argument 'city'
This happens because when we defined the print_vals() function, we specifically defined it with two keyword arguments name and age, so when the third keyword argument is passed, it should return an error.
But how can we make this function more robust so it will accept more keyword arguments as an input?
This is where **kwargs becomes handy!
Let’s rewrite the add() function to take *args as argument:
#Define function
def print_vals(**kwargs):
#Iterate over kwargs dictionary
for key, value in kwargs.items():
#Print key-value pairs
print(f'{key}: {value}')
**kwargs will allow us to pass a variable number of keyword arguments to the print_vals() function. It will be passed as a dictionary, meaning we can iterate over it using a for loop.
Let’s now test this function with sample values:
#Test with 3 keyword arguments
print_vals(name='Mike', age=20, city='New York')
#Test with 5 keyword arguments
print_vals(name='Mike', age=20, city='New York', height=6.0, weight=180)
and you should get:
name: Mike
age: 20
city: New York
name: Mike
age: 20
city: New York
height: 6.0
weight: 180
Now we made the print_vals() function more reusable by using **kwargs to make it work with a variable number of keyword arguments.
Conclusion
In this article we will explore *args and **kwards in Python and their use in functions with examples.
Now that you know the basic functionality, you can practice it by rewriting some of your existing code in different projects and try to solve for more complex use cases.
Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Python Functions tutorials.