Intermediate Chapter 79 · 25 min read · Module 6: Python Functions
*args and **kwargs
- After this chapter you can write functions that accept `*args` and `**kwargs`.
- You can explain that `args` is a tuple and `kwargs` is a dictionary.
- You can unpack a list or dictionary into a call using `*` and `**`.
- You can order parameters correctly in a function header.
- You can pass extra arguments through from one function to another.
Sometimes you do not know in advance how many values a function will receive. A function that adds prices in a shop basket may get two prices today and twenty tomorrow. Python solves this with two special parameters, written *args and **kwargs.
The star in front of a name tells Python to collect extras. One star gathers extra positional values into a tuple. Two stars gather extra named values into a dictionary. The names args and kwargs are only a habit; the stars are what matter.
The same stars also work in the opposite direction. When you call a function, * can spread a list into separate arguments and ** can spread a dictionary into named arguments. This chapter shows both directions with small, runnable examples.
Collecting positional values with *args
When a parameter name has one star, Python packs all extra positional arguments into a tuple and gives it to that name. Inside the function you can loop over it, count it with len, or index it like any tuple. If the caller passes nothing extra, args is simply an empty tuple, so your code does not crash.
def add_all(*args):
print(type(args).__name__, args)
total = 0
for n in args:
total += n
return total
print(add_all(2, 3, 5))
print(add_all())Collecting named values with **kwargs
A parameter with two stars collects every extra keyword argument into a dictionary. The keys are the argument names written as strings, and the values are what the caller passed. This is useful for options, settings, and labels where the caller picks which names to supply.
def describe(**kwargs):
print(type(kwargs).__name__)
for key in sorted(kwargs):
print(key, '=', kwargs[key])
describe(name='Asha', age=21, city='Pune')*args, then keyword-only parameters, then **kwargs. Python reports a SyntaxError for any other order.Using everything together
A single function can have a normal parameter, *args and **kwargs at once. Python first fills the normal parameters from the left, puts leftover positional values in args, and puts leftover named values in kwargs. A name that matches a normal parameter never ends up in kwargs.
def report(title, *args, **kwargs):
print('Title:', title)
print('Extra values:', args)
print('Options:', kwargs)
report('Sales', 10, 20, month='May', year=2025)Unpacking in a call
The stars have a second job at the call site. If you already hold values in a list or tuple, writing *values in the call spreads them into separate positional arguments. If you hold a dictionary, writing **options spreads it into keyword arguments. The keys of the dictionary must match parameter names, otherwise you get a TypeError.
def box(width, height, label):
return f'{label}: {width} x {height}'
size = [4, 7]
print(box(*size, label='Door'))
info = {'width': 2, 'height': 3, 'label': 'Window'}
print(box(**info))Passing arguments through
A very common pattern is a wrapper function that accepts anything and forwards it to another function. By writing def wrapper(*args, **kwargs) and calling target(*args, **kwargs), the wrapper does not need to know the details of the target. Decorators, which you will meet later, are built on this idea.
def greet(name, punctuation='!'):
return 'Hello ' + name + punctuation
def logged(*args, **kwargs):
print('calling with', args, kwargs)
return greet(*args, **kwargs)
print(logged('Ravi'))
print(logged('Mina', punctuation='?'))*args and **kwargs when flexibility really helps. For a function with a clear, fixed set of inputs, normal named parameters are easier to read and give better error messages.Keyword-only parameters after *args
Any parameter written after *args can only be given by name. This is helpful when you want to force the caller to write the option clearly. For example, def join_words(*words, sep=' ') lets the caller write join_words('a', 'b', sep='-'), but a stray positional value can never be taken as the separator by mistake. You can also write a bare * with no name to start keyword-only parameters without collecting extras.
def join_words(*words, sep=' '):
return sep.join(words)
print(join_words('red', 'green', 'blue'))
print(join_words('red', 'green', 'blue', sep='-'))When to choose each tool
Beginners often ask whether they should use *args everywhere to be safe. The answer is no. A function with clear named parameters documents itself: readers see what it needs, and Python gives a helpful error if something is missing. Use *args when the values are all of the same kind and the count truly varies, such as numbers to add or words to join. Use **kwargs when the names themselves vary, such as optional settings or extra fields in a record. When you only forward values to another function, both stars together are the right choice.
It also helps to remember the order in which Python matches arguments. First it fills normal parameters from the left using positional values. Next it gives remaining positional values to *args. Then it matches keyword arguments by name, and any name left over goes into **kwargs. If a keyword names a parameter that was already filled by position, Python raises a TypeError, because that parameter would receive two values. Keeping this order in your head makes error messages much easier to understand.
Remember that args is a tuple, so you cannot change it in place. If you need a changeable collection, convert it with list(args). In the same way, kwargs is a normal dictionary that belongs to this call only; changing it does not change the dictionary the caller used with **, because Python makes a fresh copy while unpacking.
Python syntax
def func(*args):
...def func(**kwargs):
...def func(a, *args, key=1, **kwargs):
...func(*my_list, **my_dict)Real-world applications
- Utility functions such as custom
sumormaxhelpers that accept many values. - Wrapper functions and decorators that forward calls unchanged.
- Configuration functions that accept optional settings by name.
- Building flexible logging or printing helpers.
- Calling a function with values read from a list, a file row or a JSON dictionary.
Common mistakes
**kwargs before *args in the header.Fix: Keep the order: normal parameters,
*args, keyword-only parameters, **kwargs.args with args[0] = 5.Fix:
args is a tuple. Convert it with list(args) if you need to modify it.*args without a star, so the whole list becomes one item.Fix: Write
func(*my_list) to spread the list into separate arguments.**kwargs.Fix: Check that the dictionary keys do not repeat a parameter that is already filled.
Important tips
- Name them
argsandkwargsunless a clearer name fits, such as*numbersor**options. - Write a docstring that says which extra values are expected.
- Use keyword-only parameters after
*argsfor clear options. - Print
argsandkwargswhile debugging a wrapper.
Key points summary
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.- At a call,
*unpacks a sequence and**unpacks a dictionary. - The required header order is normal,
*args, keyword-only,**kwargs. - Only the stars are special; the names are a convention.
Exam and interview points
type(args)istupleandtype(kwargs)isdict.def f(**kwargs, *args)is a SyntaxError.- Parameters after
*argsare keyword-only. f(*[1, 2])is the same asf(1, 2).f(**{'a': 1})is the same asf(a=1).
Quick revision
- One star in a header: tuple of extra positional values.
- Two stars in a header: dict of extra named values.
- One star in a call: unpack a sequence.
- Two stars in a call: unpack a dictionary.
- Order: normal, *args, keyword-only, **kwargs.
Frequently asked questions
Do I have to call them args and kwargs?
No. Any valid name works, such as `*numbers` or `**options`. The names `args` and `kwargs` are a widely used habit that other programmers will recognise.
Can I use *args without **kwargs?
Yes. Each is independent. Use `*args` alone when only positional values vary, and `**kwargs` alone when only named options vary.
What is in args when no extra values are passed?
An empty tuple, `()`. Likewise `kwargs` is an empty dictionary `{}`. Loops over them simply do nothing.
What is the difference between * in a header and * in a call?
In a header it collects extras into one name. In a call it does the reverse and spreads a sequence into separate arguments.
Practise this chapter
19 practice questions Take the chapter quiz