Lesson 8 of 19 · 2 min
kwargs — Accept Any Number of Keyword Arguments
**kwargs collects any number of named arguments into a dictionary. Useful when you need flexible configuration or optional settings.
def display_profile(**details): # **details = dict of all keyword args passed
print("=== Student Profile ===")
for key, value in details.items(): # loop through every key-value pair
print(f" {key}: {value}") # display each field
display_profile(name="Priya", age=20, branch="CSE", cgpa=3.75)
print("---")
display_profile(name="Ahmed", year=2) # completely different keys — still works!
Output: === Student Profile === name: Priya age: 20 branch: CSE cgpa: 3.75 === Student Profile === name: Ahmed year: 2
Combining args and *kwargs Together
def demo(a, b, *args, **kwargs): # fixed params first, *args, then **kwargs
print(f"Required: a={a}, b={b}") # positional required args
print(f"Extra positional: {args}")# extra positional → tuple
print(f"Keyword args: {kwargs}") # named keyword args → dict
demo(1, 2, 3, 4, 5, name="Ravi", city="Chennai")
Output:
Required: a=1, b=2
Extra positional: (3, 4, 5)
Keyword args: {'name': 'Ravi', 'city': 'Chennai'}