Search for Courses, Topics

*Args and **Kwargs in Python

Learn about *args and **kwargs in Python.

29 Aug 2021-6 mins read
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

*args specifies the number of non-keyworded arguments that can be passed and the operations that can be performed on the function in Python whereas **kwargs is a variable number of keyworded arguments that can be passed to a function that can perform dictionary operations.

Scope

  • In this article, we will see why we need *args and **kwargs and how they can be useful in solving specific problems.
  • Then, we will learn about *args and **kwargs in Python along with their syntaxes and examples.
  • Then we will learn about packing and unpacking in Python using *args and **kwargs along with some examples.

Args and Kwargs in python

Why do we need *args and **kwargs?

When we are writing Python code, functions are something that we cannot overlook. Functions are beneficial in removing the repetition of code and making it modular . Functions generally need some data to work on, and it can be in the form of strings, numbers, or even other functions. In the programming world, this data is referred to as arguments.

A simple scenario where you will need functions is- Suppose you are running a website to design greeting cards. If you want to display a greeting message like “Hello name_of_user”, you must ask the user to input their name. You will then pass the input to a function that will display the greeting message.

Sometimes it is possible that you can't predict the number of arguments that we will be providing to the function. This can cause the problem, and if you don’t know how to handle it, then you will end up getting stuck writing the same code for variable number of arguments.

*args are **kwargs are the solution of your problem.

*args in Python

Let us assume that you are building a calculator which only performs multiplication.

You can make a simple function that can do this and that function will look like this-

def multiply(num1,num2):
    return num1*num2
 
print("product:", multiply(2,3)) 

Output:

product:6

Now you want to multiply three numbers, so you have to make a new function.

def multiplyThreeNumbers(num1, num2, num3):
    return num1*num2*num3
 
print("product:",multiplyThreeNumbers(1, 2, 3))

Output:

product:6

You can already see the problem. If you keep going on like this, you will end up doing a lot of functions.

*args can save you the trouble here.

You can use args to solve this problem in a simple and flexible piece of code-

def multiplyNumbers(*numbers):
    product=1
    for n in numbers:
        product*=n
    return product
 
print("product:",multiplyNumbers(4,4,4,4,4,4)) 

Output:

product:4096

Now that your problem is solved let’s understand what is going on here.

Python has *args, which allows us to pass a variable number of non-keyword arguments to a function. Non-keyword here means that the arguments should not be a dictionary (key-value pair), and they can be numbers or strings.

One thing to note here is that "args" is just an identifier. It can be named anything relevant.

When an asterisk(*) is passed before the variable name in a Python function, then Python understands that here the number of arguments is not fixed. Python makes a tuple of these arguments with the name we use after the asterisk(*) and makes this variable available to us inside the function. This asterisk(*) is called an “unpacking operator”. We will learn more about it further on in the article.

This variable is then available to us inside the function, and we can use it to perform any operation we want. In our case, we iterated (looped) over it and calculated the product of all the numbers.

**kwargs in Python

*args enable us to pass the variable number of non-keyword arguments to functions, but we cannot use this to pass keyword arguments. Keyword arguments mean that they contain a key-value pair, like a Python dictionary.

**kwargs allows us to pass any number of keyword arguments.

In Python, these keyword arguments are passed to the program as a Python dictionary.

Python will consider any variable name with two asterisks(**) before it as a keyword argument.

def makeSentence(**words):
    sentence=''
    for word in words.values():
        sentence+=word
    return sentence
 
print('Sentence:', makeSentence(a='Kwargs ',b='are ', c='awesome!'))

Output:

Sentence:Kwargs are awesome! 

In the makeSentence function, we are iterating over a dictionary, so we have to use values() to use the values. Otherwise, it will only return the keys and not the values.

Another example of how kwargs can be used is given below-

def whatTechTheyUse(**kwargs):
    result = []
    for key, value in kwargs.items():
        result.append("{} uses {}".format(key, value))
    return result
 
print(whatTechTheyUse(Google='Angular', Facebook='react', Microsoft='.NET'))

Output:

[‘Google uses Angular’, ‘Facebook uses react’, ‘Microsoft uses .NET’]

In this code, we have used .items() because we want to get both the key and the value.

Using Both *args and *kwargs in a Python Function

Now that you have understood args and *kwargs, you might want to design a function that uses both of them. While doing this, the order of the arguments matter, *args has to come before *kwargs.

So if you are using standard arguments along with *args and **kwargs, then you have to follow this order-

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

A simple example of a function that uses standard arguments, *args and **kwargs in Python:

def printingData(codeName, *args, **kwargs):
    print("I am ", codeName)
    for arg in args:
        print("I am arg: ", arg)
    for keyWord in kwargs.items():
        print("I am kwarg: ", keyWord)
 
printingData('007', 'agent', firstName='James', lastName='Bond') 

Output:

  I am 007 
  I am arg: agent 
  I am kwarg: (‘firstName’, ‘James’) 
  I am kwarg: (‘lastname’ , ‘Bond’)

Packing and Unpacking Using *args and **kwargs in Python

The single and double asterisks that we use are called unpacking operators.

Unpacking operators are used to unpack the variables from iterable data types like lists, tuples, and dictionaries.

A single asterisk(*) is used on any iterable given by Python.

The double asterisk(**) is used to iterate over dictionaries.

Let’s take some examples-

carCompany = ['Audi','BMW','Lamborghini']
print(*carCompany)

Output:

Audi BMW Lamborghini

Here the asterisk(*) passed before carCompany unpacked all the values. In other words, the values are printed as separate strings rather than a list.

techStackOne = {"React": "Facebook", "Angular" : "Google", "dotNET" : "Microsoft"}
techStackTwo = {"dotNET" : "Microsoft"}
mergedStack = {**techStackOne, **techStackTwo}
print(mergedStack)

Output:

{'React': 'Facebook', 'Angular': 'Google', 'dotNET': 'Microsoft'}

Here the double-asterisk unpacked the key-value pairs inside the mergedStack variable, and thus we get all the key-value pairs in the mergedStack variable. args and kwargs in Python do the same job of unpacking the contained values, but they take different inputs and outputs.

Conclusion

After learning about *args and **kwargs in Python, you can now successfully utilize their superpowers.

Here are some key points that will help you-

  • *args and **kwargs are special Python keywords that are used to pass the variable length of arguments to a function
  • When using them together, *args should come before **kwargs
  • The words “args” and “kwargs” are only a convention, you can use any name of your choice
Challenge Time!
quiz Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
certificate icon
Certificates
Python Tutorial
Module Certificate
Criteria
You’ll be able to claim a certificate for any course you have access to only after you’ve spent enough time learning. The time required is determined by the length of the course.
Certificates are a fantastic way to showcase your hard-earned skills to employers, universities, and anyone else that may be interested. They provide tangible proof that you’ve completed a course on Scaler Topics. In many cases they can help you claim a training reimbursement or get university credit for a course.