Software, Tech & Coding simplified.

What Is ** in Python?

black and white computer keyboard

A Python function that takes **kwargs as an argument accepts any number of keyword arguments.

For example:

def info(**kwargs):
    for name, number in kwargs.items():
        print(f'Player {name} has a number {number}')

Now you can call the function with any number of keyword arguments:

info(Ronaldo=7, Messi=10, Bale=9)
info(Messi=10, Bale=9)
info(Ronaldo=7)

To deeper understand args and kwargs in Python, keep on reading.

Arguments in Python

Before learning what keyword arguments are, it’s worthwhile to have a look at the argument types of Python.

In Python, there are three types of arguments:

  1. Default arguments.
  2. Positional arguments (regular arguments).
  3. Keyword arguments.

Let’s take a brief look at each of these argument types.

1. Default Arguments in Python

Although the main focus of this article is not on default arguments, let’s briefly go through them.

In Python, a default argument means a function argument has a default value. This means you can call the function with or without an argument (or arguments).

Let’s see an example.

Here is a function that takes a default argument as its parameter:

def greet(name="friend"):
    print("Hello", name)

greet()
greet("Jack")

Output:

Hello friend
Hello Jack

Here, the default value friend is used if the name is not specified when calling the function.

2. Positional Arguments (Args) in Python

Positional arguments are the “regular” arguments you use all the time. They need to be included in the right order in a function call.

For example, here is a function that accepts two arguments:

def greet(firstname, lastname):
    print("Hello", firstname, lastname)

Now you can call this function by providing the two arguments as positional arguments like this:

greet("Jack", "Jones")

Output:

Hello Jack Jones

The key takeaway here is that the order matters. Calling the function this way expects the first argument to be the firstname and the second one to be the lastname.

But, there’s another way to call this function. You can also provide the arguments as keyword arguments. Next, we are going to see how to do it.

3. Keyword Arguments (Kwargs) in Python

In the previous example, you learned how positional arguments work.

If you pass a function with some positional arguments, you are expected to call the function with the arguments in the right order. But you can also pass arguments as keyword arguments. When using keyword arguments, the order doesn’t matter anymore.

Let’s use the above greet() function for demonstration. To pass the firstname and lastname as keyword arguments, name the arguments this way:

greet(lastname="Jones", firstname="Jack")

As you can see, this function call works no matter in which order you pass the arguments to the function.

Hello Jack Jones

Now you understand the different argument types of Python.

Next up, let’s see how to create functions that accept any number of arguments in Python.

*Args in Python—Any Number of Arguments

In Python, it is possible to give any number of (positional) arguments into a function. To do this, use the asterisk * in front of the argument name.

For instance, let’s create a function that sums up any number of numbers:

def sumAny(*args):
    s = 0
    for num in args:
        s += num
    return s

Now you can call this function with any number of arguments:

print(sumAny(1, 2))
print(sumAny(1, 2, 3, 4))

Output:

3
10

Under the hood, the *args becomes a list of the given arguments. This is why it’s possible to loop it through the same way as looping any other list in Python.

**Kwargs in Python—Any Number of Keyword Arguments

In Python, it’s possible to give a function any number of keyword arguments. To do this, the function must accept an argument that is marked with the double-asterisk **.

For instance, let’s create a function that accepts any number of keyword arguments.

def info(**kwargs):
    for name, number in kwargs.items():
        print(f'Player {name} has a number {number}')

You can pass any number of player data items to this function. The double asterisk makes the Python interpreter understand that the function should accept keyword arguments.

Let’s make some example calls to this function:

info(Ronaldo=7, Messi=10, Bale=9)
info(Bale=9, Ronaldo=7)

Output:

Player Ronaldo has a number 7
Player Messi has a number 10
Player Bale has a number 9

Player Bale has a number 9
Player Ronaldo has a number 7

This works under the hood by converting the keyword arguments into a dictionary of key-value pairs. This makes it possible to handle the arguments like any other dictionary in Python.

Use Both *args and **kwargs in Python Functions

It is possible to make a function accept both any number of arguments and any number of keyword arguments. The Python interpreter has no problem with this, as it can determine the types of arguments on the fly.

For instance, let’s create a function that takes any number of spectator names and any amount of player data as its arguments:

def info(*args, **kwargs):
    print("Soccer Game: \n")
    for name, number in kwargs.items():
        print(f"{name} plays with number {number}")
    print("")
    for spectator in args:
        print("Welcome to watch the game", spectator)

Now you can call this function with any number of spectators and any amount of player data:

info("Jack", "Sophie", "Jon", "Matt", Ronaldo=7, Messi=10, Bale=9)

Output:

Soccer Game: 

Ronaldo plays with number 7
Messi plays with number 10
Bale plays with number 9

Welcome to watch the game Jack
Welcome to watch the game Sophie
Welcome to watch the game Jon
Welcome to watch the game Matt

*args and **kwargs in Python—A Naming Convention

Finally, it’s important you understand there’s nothing interesting in the names args and kwargs in Python. These are not reserved keywords. You could use any other argument name instead.

For example:

def sumAny(*numbers):
    s = 0
    for num in numbers:
        s += num
    return s

Or as another example:

def info(**playerdata):
    for name, number in playerdata.items():
        print(f'Player {name} has a number {number}')

As you can see, it doesn’t matter what you call the keyword arguments. The only two things to keep in mind are:

  • Use * when you want to accept any number of regular (positional) arguments.
  • Use ** when you want to accept any number of keyword arguments.

Wrap Up

In Python, it’s possible to call a function with an arbitrary number of arguments. This can be applied to regular arguments or keyword arguments. To call a function with any number of arguments the function has to use:

  • * in front of the argument name to accept any number of regular arguments.
  • ** in front of the argument, name to accept any number of keyword arguments

Here is an example of a function that accepts any number of keyword arguments:

def info(**kwargs):
    for name, number in kwargs.items():
        print(f'Player {name} has a number {number}')

# You can call this function with any amount of player data:
info(Ronaldo=7, Messi=10, Bale=9)
info(Bale=9, Ronaldo=7)

And here’s one that takes any number of regular arguments:

def sumAny(*args):
    s = 0
    for num in args:
        s += num
    return s

# You can call this function with any number of numbers
print(sumAny(1,2,3))
print(sumAny(1,2,3,4,5))

Also, feel free to change the names of the args and kwargs as you wish. They are not reserved keywords in Python.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

Share

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email