The One Rule for Calling the Function
If you mix positional (unnamed) inputs and keyword (named) inputs in your function call, all positional inputs must come first.
# 'size' is required. 'sugar' and 'milk' are optional.
def make_coffee(size, sugar=2, milk=True):
print(f"Size: {size}, Sugar: {sugar}, Milk: {milk}")
# CORRECT: Positional ("Large") comes before keyword (milk=False)
make_coffee("Large", milk=False)
# INCORRECT: SyntaxError - Positional argument follows keyword argument
make_coffee(size="Large", 0, False)The concepts of *args and **kwargs are incredibly powerful in Python. They allow you to write flexible functions that don’t need to know in advance exactly how many inputs they will receive.
Here is a detailed breakdown of how they work under the hood.
1. *args (Arbitrary Positional Arguments)
The single asterisk (*) is the magic piece here. When you place it before a parameter name in a function definition, it tells Python: “Take any extra positional arguments the user provides, and pack them all together into a single Tuple.”
This is perfect for functions that perform an operation on a batch of items, like summing numbers.
Python
def sum_all_numbers(*args):
# 'args' is now a tuple containing all passed values
print(f"Inside the function, args looks like this: {args}")
total = 0
for num in args: # Because it's a tuple, you can loop through it
total += num
return total
# We can pass 2 arguments, 5 arguments, or none at all!
print(sum_all_numbers(10, 5))
print(sum_all_numbers(1, 2, 3, 4, 5))
Output:
Plaintext
Inside the function, args looks like this: (10, 5)
15
Inside the function, args looks like this: (1, 2, 3, 4, 5)
15
2. **kwargs (Arbitrary Keyword Arguments)
The double asterisk (**) handles named arguments (e.g., age=25). It tells Python: “Take any extra keyword arguments the user provides, and pack them into a Dictionary.” The parameter name becomes the dictionary key (as a string), and the passed value becomes the dictionary value.
This is highly useful for functions that build configurations, profiles, or handle optional settings.
Python
def build_user_profile(username, **kwargs):
# 'kwargs' is a dictionary containing all extra named inputs
print(f"Inside the function, kwargs looks like this: {kwargs}")
# We can create a base dictionary and update it with the kwargs
profile = {"user": username}
profile.update(kwargs)
return profile
# We can pass as many custom named arguments as we want
user1 = build_user_profile("alice123", email="alice@test.com", age=28)
user2 = build_user_profile("bob99", role="Admin", active=True, location="NY")
Output:
Plaintext
Inside the function, kwargs looks like this: {'email': 'alice@test.com', 'age': 28}
Inside the function, kwargs looks like this: {'role': 'Admin', 'active': True, 'location': 'NY'}
3. The Asterisks Are the Only Rule
While you will almost always see them written as *args and **kwargs, the words “args” and “kwargs” are just strong community conventions. The asterisks do all the actual work.
You could legally write def multiply(*numbers): or def set_config(**options):, and it would work exactly the same way. However, sticking to *args and **kwargs makes your code instantly readable to other Python developers.
4. The Strict Ordering Rule
If you want to use standard parameters, default parameters, *args, and **kwargs all in the exact same function, you must define them in a very specific order. If you mix up this order, Python will throw a SyntaxError.
The correct order is:
-
Standard positional arguments (e.g.,
a, b) -
*args -
Keyword arguments with default values (e.g.,
c=10) -
**kwargs
Example of a fully loaded function:
Python
def complex_function(a, b, *args, c=10, **kwargs):
print(f"a: {a}, b: {b}")
print(f"args: {args}")
print(f"c: {c}")
print(f"kwargs: {kwargs}")
# Calling it:
complex_function(1, 2, 3, 4, 5, c=99, name="Dave", status="Online")
Output:
Plaintext
a: 1, b: 2
args: (3, 4, 5)
c: 99
kwargs: {'name': 'Dave', 'status': 'Online'}
In this execution:
-
1and2go to the requiredaandb. -
3,4, and5are scooped up by*argsinto a tuple. -
c=99overrides the default value of 10. -
nameandstatusare scooped up by**kwargsinto a dictionary.