Python / Core Python Fundamentals Interview Questions
What are *args and **kwargs in Python function definitions?
*args and **kwargs are conventions (the names are arbitrary; the stars are what matter) for writing functions that accept a variable number of arguments.
def log(level, *messages, separator='|', **meta): joined = separator.join(messages) extra = ', '.join(f'{k}={v}' for k, v in meta.items()) print(f'[{level}] {joined} ({extra})') log('INFO', 'Server started', 'Listening on port 8080', separator=' â ', host='localhost', port=8080) # [INFO] Server started â Listening on port 8080 (host=localhost, port=8080)
*args collects any extra positional arguments beyond the explicitly named ones into a tuple. **kwargs collects any extra keyword arguments into a dict. Both are optional — you can use either, both, or neither.
The same syntax works on the call side to unpack sequences and mappings:
def add(a, b, c): return a + b + c nums = [1, 2, 3] config = {'a': 10, 'b': 20, 'c': 30} print(add(*nums)) # 6 â unpacks the list print(add(**config)) # 60 â unpacks the dict as keyword args
A common use case is writing wrapper or decorator functions that forward all arguments to an inner function without knowing what those arguments are. The canonical pattern is def wrapper(*args, **kwargs): return original(*args, **kwargs).
More Related questions...