Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

What is the **kwargs keyword in Python?

Vinisha Maheshwari

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will discuss the **kwargs keyword in Python. Python functions are built to lessen the redundancy of the same program and make the code reusable. Usually a function is written with a specific value called an argument. However, that sometimes creates problems if the number of arguments is not known.

The **kwargs keyword

Let’s say we want to create a function which gives us the name and age of a person. In this case, we might not know how many variables we want to add. We use **kwargs to address this problem.

**kwargs allows us to pass a variable number of keyword arguments to the function by using double asterisk ** before the parameter name. The arguments are passed as a dictionary. **kwargs is a special keyword that makes the function flexible.

Code

Let’s look at the code snippet to understand this better.

def intro(**data):
for key, value in data.items():
print(f"{key} is {value}")
intro(Name="Tom", Age=25)
intro(Name="Jerry", Age=26)
Using **kwargs keyword in Python

Explanation

  • In line 1, we create a function.

  • In lines 3 and 4, we create a loop which prints both the key and value of the input dictionary.

  • In lines 6 and 7, we run the function using sample inputs.

In this way, we can use the **kwargs keyword in Python.

RELATED TAGS

communitycreator
python

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring