/  Technology   /  What Are *args and **kwargs in Python?

What Are *args and **kwargs in Python?

The generally associated operator with multiplication is splat operator, but in Python it doubles as the splat operator.

A simple example will make this clearer.

 

>>>x = [1,2,3]
>>>y = [*a,7,8,9]
>>>print(y)
[1,2,3,7,8,9]

 

In the above example, we’re taking the contents of x and splattering that is unpacking it into our new list y.

 

How To Use *args and **kwargs?

 

The splat operator unpacks multiple values, and there are two types of function parameters namely *args short for arguments, and **kwargs short for keyword arguments.

Each of the parameter is used to unpack their respective argument type and allow function calls with variable-length argument lists. Let’s see with an example.

 

Example:

 

def printScores(TeamHead, *scores):
 print(f"TeamHead Name: {TeamHead}")
 for score in scores:
   print(score)
printScores("Vicky",100, 95, 88, 92, 99)

 

Output:

 

What Are *args and **kwargs in Python?

 

In above example we have not used *args , because “args” is a standard convention but still just a name. The *args, a single asterisk is the main parameter here, creating a list whose elements are positional arguments — after those defined — from the function call.

With that cleared up, **kwargs should be an easy to digest. There is no matter with the name, but the double asterisks create a dictionary whose items are keyword arguments — after those defined — from a function call.

 

To illustrate this, let’s take an example.

 

def printNames(website, **courses):
 print(f"Website Name: {website}")
 for course,name in courses.items():
   print(f"{course}: {name}")
printNames("i2tutorials", Programming="Python", Database=["Mongodb", "Cassandra", "MySql"], DataScience="MachineLearning")

 

Output:

 

What Are *args and **kwargs in Python?

Leave a comment