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 argsA 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).
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
