Syntax
def func(*args, **kwargs):Examples
Using *args
Accepting any number of positional arguments.
def sum_all(*numbers):
total = 0
for n in numbers:
total += n
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(10, 20, 30, 40)) # 100
print(sum_all()) # 0Using **kwargs
Accepting any number of named keyword arguments.
def print_profile(**details):
for key, value in details.items():
print(f"{key}: {value}")
print_profile(name="John", age=21, course="Software Engineering")Combining Both
A function that accepts regular parameters, extra positional args, and extra keyword args together.
def describe(title, *args, **kwargs):
print(f"Title: {title}")
print(f"Extra positional: {args}")
print(f"Extra keyword: {kwargs}")
describe("Report", "Q1", "Q2", author="John", pages=12)
# Title: Report
# Extra positional: ('Q1', 'Q2')
# Extra keyword: {'author': 'John', 'pages': 12}Unpacking When Calling
* and ** also work in reverse - spreading an existing list/dict into a function call.
def add(a, b, c):
return a + b + c
values = [1, 2, 3]
print(add(*values)) # 6
info = {"a": 10, "b": 20, "c": 30}
print(add(**info)) # 60Best practices
- Use *args when the number of positional inputs varies, and **kwargs when you want named, optional configuration options
- Place *args and **kwargs after any required named parameters in a function signature (def func(a, b, *args, **kwargs))
- Use **kwargs sparingly in your own APIs - overly flexible signatures can make it unclear what arguments are actually expected
- Combine *args/**kwargs with function wrappers or decorators when you need to pass arguments through to another function unchanged
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference