*args and **kwargs in Python

Jas Spencer
2 min readApr 22, 2021

These two terms can cause a lot of uneasy feelings when seeing them for the first time. Actually they provide a lot of assistance to Python functions, using *args and **kwargs make it easier for functions to accept multiple arguments which in turn can prevent projects from breaking if the user does something unpredictable.

In order to understand these two terms, we need to understand the basic outline of a function. When writing a function, we expect it to take in arguments that will be passed through as parameters in order to complete the function. A very basic example:

def add_to_numbers(num1, num2):
print(num1 + num2)

With this function, whatever two numbers that get passed in will be added together. But passing in any other number of arguments will result in an error. This method can only add two numbers, not three or four or… you get the idea.

Here is where we can use *args, which allows the function to accept any number of positional arguments, with some slight adjustments to the above function, we can make it much more versatile:

Note: the asterisk (*) must be included other wise the logic won’t work, we don’t even have to follow it with ‘args’, anything will work but ‘args’ is the most common and makes the most sense.

def add_any_numbers(*args):
total = 0
for number is args:
total +=number
print("Total sum is: ", total)

This function does the same as the first example, but now we can take in any number of arguments and the new logic in the function will loop through each of them, no matter how many are passes in, and print out the total sum. Just like that, our adding function has become much more dynamic!

**kwargs is used for taking in keyword or named arguments, and is used whenever an arbitrary number of keyword arguments get passed in as a parameter. Just as with *args, the asterisk is the most important thing, naming it ‘kwargs’ is just convention, but if it ain’t broke…

def print_stuff(**kwargs):
print(kwargs)
print_stuff(a=1, b=2, c="Hello World")this returns:{'a': 1, 'b': 2, 'c': "Hello World"}

You’ll notice that the method has turn our **kwargs into a dictionary with key:value pairs. This is useful as now we can perform all the dictionary operations on it.

*args and **kwargs can be a Python developers best friend. Using them help functions become more dynamic as they accept multiple arguments and of different types. As every programmer knows, the more you can do with just one function, means you ultimately have to do less!

--

--

Jas Spencer

Software Engineer in NYC with expertise in Ruby on Rails, JavaScript, and React