Python — A Guide to the Star or Asterisk Operator / (** ) **args or ***kwargs

In this short tutorial, we will see different ways in which Asterisk Operator can make our Pythonic Life Easy!

Shelvi Garg
Python in Plain English

--

Image Reference

There are many times when we see * and ** operators being used in Python. Many Python Programmer even at the intermediate level is often puzzled when it comes to the asterisk ( * ) character in Python.

After studying this article, you will have a solid understanding of the asterisk ( * ) operator in Python and become a better coder in the process!

We already know the multiplication functionality of *. Let’s get a quick review:

Simple Multiplication:

print(5*4)20

Exponential value of any integer value:

print(2**2)4

Multiplication of a List

list = ['name '] * 5

print(list)
['name ', 'name ', 'name ', 'name ', 'name ']

Less Known Uses:

Before you get started, you should know:

Positional arguments: are arguments that can be called by their position in the function definition.

Keyword arguments: are arguments that can be called by their name.

Required arguments: are arguments that must be passed to the function.

Optional arguments: are arguments that can be not passed to the function

Case 1: Unpacking a function using positional argument:

This method is very useful while printing your data in a raw format (without any comma and brackets ). Many of the programmers trying to remove comma and brackets by using a convolution of functions, Hence this simple prefix asterisk can solve your problem in unpacking them.

arr = ["Monday","Tuesday","Wed","Thurs"]
print(" ".join(map(str,arr)))
print(*arr)
Monday Tuesday Wed Thurs
Monday Tuesday Wed Thurs

As you can see, both line 2 of the above code and line 3 give the same result, the line 3 of the code using asterisk is much easier than any other.

Case 2: Passing a Function with an arbitrary number of arguments using *

Single asterisk( * ) can also be used in *args. It is used to pass a number of variable arguments to a function, it is mostly used to pass a non-key argument and variable-length argument list. Note: NON-KEY ARGUMENT

Let’s see with an example:

def addition(*args):
return sum(args)

print(addition(8,9,7,0))
24

Case 3: Passing a Function with an arbitrary number of a positional argument

The double asterisk( ** ) is also used as **kwargs, the double asterisks allow passing keyword argument. This special symbol is used to pass keyword arguments and variable-length argument lists.

def food(**kwargs):
for item in kwargs:
print(f"{item} is a {kwargs[item]}")

food(cherry="fruit",cabbage="vegetable",soya="protein")
cherry is a fruit
cabbage is a vegetable
soya is a protein

Passing as Dictionary

def food(**kwargs):
for item in kwargs:
print(f"{item} is a {kwargs[item]}")

dict = {"cherry":"fruit","cabbage":"vegetable","soya":"protein"}

food(**dict)
cherry is a fruit
cabbage is a vegetable
soya is a protein

kwargs and args

In the above cases we saw the use of kwargs and args, now let’s see in detail what are kwargs and args with examples and different ways to use them in code.

In Python, we can pass a variable(non-fixed) number of arguments to a function using special symbols. There are two special symbols used for this:

Special Symbols Used for passing variable no. of arguments:-

1.)*args: for Non-Keyword Arguments

2.)**kwargs: for Keyword Arguments

Thus, (*)/*args/**kwargs is used as the wildcard for our function’s argument when we have doubts about the number of arguments we should pass in a function!

Example for *args:

Using args for a variable number of arguments:

def var_arg(*argv):
for arg in argv:
print(arg)

var_arg("Ram","Sita","Ravan","Lakshman","Hanuman","Mandodri")
Ram
Sita
Ravan
Lakshman
Hanuman
Mandodri

Using *args for an extra argument + variable number of arguments

def var_arg(arg1,*argv):
print("extra argument: ",arg1)
for arg in argv:
print(arg)

var_arg("Introducing","Ram","Sita","Ravan","Lakshman","Hanuman","Mandodri")
extra argument: Introducing
Ram
Sita
Ravan
Lakshman
Hanuman
Mandodri

So, what are **kwargs??

**kwargs in function definitions are used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).

One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.

Example for **kwargs:

Using **kwargs for a variable number of keyword arguments

def var_arg(**kwargs):
for key,value in kwargs.items():
print("%s:%s" %(key,value))

#Driver code
var_arg(Ram ="Sita",Ravan="Mandodri")
Ram: Sita
Ravan: Mandodri

Using *kwargs for an extra argument + variable number of keyword arguments

def var_arg(arg1,**kwargs):
print(arg1)
for key,value in kwargs.items():
print("%s:%s" %(key,value))

#Driver code
var_arg("Couples",Ram ="Sita",Ravan="Mandodri")
Couples
Ram:Sita
Ravan:Mandodri

Let get more clarity for kwargs and args with 2 more examples.

Using *args and **kwargs to call a function:

def fun(*args, **kwargs):
for arg in args:
print(arg)

for key,value in kwargs.items():
print("%s:%s" %(key,value))

fun("Ram", "Ravan", "Lakshman")


fun(Ram = "Sita", Ravan = "Mandodri", Lakshman = "Urmila")
Ram
Ravan
Lakshman
Ram:Sita
Ravan:Mandodri
Lakshman:Urmila

Key Notes: Always Remember :

Single Asterisk (*): Non-Key Arguments, Variable Length Argument

Double Asterisk (**): Key-Word Argument, Variable Length Arguments

Hurray, you made it to the end!!

I hope the concept of Asterisk, kwargs, and args are clearer to you now.

Here sending more stars and shine your way :)

Image Ref: Adobe Stock

Cheers!

References:

More content at plainenglish.io

--

--