*args and **kwargs in Python
Sometimes we don't know how many values will be passed to a function. In such cases, Python provides two special symbols:
*args→ to accept many positional arguments**kwargs→ to accept many keyword (named) arguments
What is *args?
*args allows a function to take any number of values (without names). These values are
stored as a tuple.
Example: Using *args
def total_marks(*args):
sum = 0
for mark in args:
sum += mark
print("Total Marks:", sum)
total_marks(70, 80, 90)
Output:
Total Marks: 240
Explanation:
*argscollects (70, 80, 90) as a tuple.- The loop adds each value one by one.
- Finally, the total is printed.
What is **kwargs?
**kwargs allows a function to take any number of named arguments.
These arguments are stored in the form of a dictionary.
Example: Using **kwargs
def student_info(**kwargs):
for key, value in kwargs.items():
print(key + ":", value)
student_info(name="Vanshu", age=19, course="Python")
Output:
name: Vanshu
age: 19
course: Python
Explanation:
**kwargscollects all arguments as key-value pairs.- These are printed using a loop over the dictionary.
Using both *args and **kwargs in one function
def show_all(*args, **kwargs):
print("Values:", args)
print("Named Info:", kwargs)
show_all(10, 20, name="Simran", subject="Python")
Output:
Values: (10, 20)
Named Info: {'name': 'Simran', 'subject': 'Python'}
Explanation:
*argsstores (10, 20) in a tuple.**kwargsstores {'name': 'Simran', 'subject': 'Python'} as a dictionary.
Summary Table:
| Term | Used For | Stored As |
|---|---|---|
*args |
Multiple values (without names) | Tuple |
**kwargs |
Multiple values (with names) | Dictionary |
Key Points to Remember:
*argslets us pass many values without names.**kwargslets us pass many values with names.- They make our functions more flexible.
- We can use both in the same function, but
*argsmust come before**kwargs.