Python · The language, not just syntax
How do *args and **kwargs work?
Short answer
*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. At a call site the same syntax unpacks an iterable or mapping.
The stars are packing operators in a function signature and unpacking operators at a call site. They are not special names; args and kwargs are just conventions. Parameters after a bare star are keyword-only.
def configure(host, *flags, port=8000, **options):
print(host, flags, port, options)
settings = {"port": 9000, "debug": True}
configure("api.local", "verbose", "dry-run", **settings)
def forward(*args, **kwargs):
return configure(*args, **kwargs)Rules to remember
- Order: positional, *args, keyword-only, **kwargs
- A bare * in the signature makes following parameters keyword-only
- A bare / makes preceding parameters positional-only
- Unpacking a dict with duplicate explicit keywords raises TypeError
The pattern is essential for decorators and wrappers because it forwards arbitrary signatures. It also makes APIs harder to discover, so do not use it when explicit parameters would document the interface better.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between *args and a list parameter?
- 2How do you make a keyword-only argument?
- 3What order must parameters follow in a signature?
- 4How do decorators use *args and **kwargs?
Say it in the interview
Star args pack extra positional arguments into a tuple, and double-star kwargs pack extra keywords into a dict. At a call site the same syntax unpacks values. The main use is forwarding through decorators and wrappers. I keep explicit parameters when the API is public, because star args hide the signature, and I use a bare star for keyword-only options to prevent positional mistakes.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.