A quick introduction to *args and **kwargs in Python!

Sometimes you might need to create a function with multiple parameters.

Let's say you need to create a function that adds an arbitrary amount of numbers. But beforehand, you don't know the number of parameters. How would you implement it?

Here is what a trivial solution might look like :

def addNumbers(numbers=[]):
    total = 0
    for number in numbers:
        total += number
    return total
print(addNumbers([1,2,3,4,5])) #prints 15

We can archive the same effect by using the *args syntax in Python.

Using *args

args is like a list, the function with the args parameter can accept any amount of parameters and stores them in a list.

By iterating over the list, we can process the parameters in any way we would like to :

def addNumbers(*args):
    total = 0
    for number in args:
        total += number
    return total

print(addNumbers(1,2,3,4,5)) #prints 15

Using **kwargs

*kwargs is almost the same as args, but the function would be able to accept any named parameters, and stores them in a dictionary.

We can access the information like we did with *args, by using dictionary iterating functions

def addNumbers(**kwargs):
    total = 0
    for number in kwargs.values():
        total += number
    return total

print(addNumbers(n1=1, n2=2, n3=3, n4=4, n5=5)) #prints 15

args and *kwargs are convention, you can name them however way you want to in your code!

def addNumbersArgs(*numbers):
    total = 0
    for number in numbers:
        total += number
    return total

def addNumbersKwargs(**numbers):
    total = 0
    for number in numbers.values():
        total += number
    return total

print(addNumbersArgs(1,2,3,4,5)) #prints 15
print(addNumbersKwargs(n1=1, n2=2, n3=3, n4=4, n5=5)) #prints 15

Important Tip!

The ordering of the args and *kwargs do matter!

The correct ordering of parameters in a function is

  1. Standard parameters
  2. *args parameters
  3. *kwargs parameters

Here are two functions, the first function implements args and *kwargs incorrectly ad the second one is the correct way

#Wrong! **kwargs should come after *args 
def exampleFunction(a, b, **kwargs, *args):
    pass

#The correct way!
def exampleFunction2(a, b, *args, **kwargs):
    pass

That's all!

I hope you learned something from this thread! If you did, please RT and follow for more Python-related tips! Thanks and follow me on Twitter to get posted on more content related to Python!