Intermediate   Chapter 78 · 25 min read · Module 6: Python Functions

Variable-Length Arguments

Learning objectives
  • After this chapter you can explain why a function may need a variable number of arguments.
  • You can define a function that collects extra positional arguments with *args.
  • You can define a function that collects extra keyword arguments with **kwargs.
  • You can combine normal parameters, *args and **kwargs in the correct order.
  • You can loop over the collected values and handle the case when nothing is passed.

Most functions you have written so far take a fixed number of arguments. A function with two parameters must be called with two values. But real programs often need more freedom. Think of a function that adds numbers: sometimes you add two numbers, sometimes ten. Writing a new function for every count would be silly.

Python solves this with variable-length arguments. By placing a single star before a parameter name, you tell Python to collect all extra positional values into one tuple. By placing two stars before a name, you ask Python to collect all extra keyword values into a dictionary. The function then works with those collections like any other tuple or dictionary.

In this chapter you will learn the basic idea, the rules for ordering parameters, and the common patterns for looping over the collected values. The next chapter goes deeper into the names *args and **kwargs and into unpacking at the call site.

Why fixed arguments are not always enough

A normal parameter list has an exact size. If you define def add(a, b), then calling add(1, 2, 3) raises a TypeError because three values were given for two slots. This is a good protection in most cases, because it catches mistakes early. However, some tasks are naturally open-ended. The built-in print accepts any number of values, and max accepts two values or twenty. You can write your own functions with the same flexibility.

Collecting positional arguments with a star

When a parameter name starts with one star, Python gathers all the positional arguments that do not match earlier parameters and packs them into a tuple. The name after the star is your choice, but programmers almost always write args. Inside the function, args is a normal tuple, so you can use len(args), indexing, slicing, sum(args) and a for loop.

Variable-length argument: a parameter that can receive any number of extra values, so the caller decides how many to pass
Example 1: a sum function with *args
def total(*args):
    print("type:", type(args).__name__)
    print("count:", len(args))
    return sum(args)

print(total(1, 2, 3))
print(total(10, 20, 30, 40, 50))
print(total())
type: tuple count: 3 6 type: tuple count: 5 150 type: tuple count: 0 0

Notice that total() with no arguments works. The tuple is simply empty and sum of an empty tuple is 0. This is a useful feature, but you should think about whether an empty call makes sense for your function. A function that finds the largest value should probably complain when there is nothing to compare.

Collecting keyword arguments with two stars

Keyword arguments are values passed with a name, like city="Pune". When a parameter name starts with two stars, Python gathers all keyword arguments that do not match a named parameter and packs them into a dictionary. The keys are the names as strings and the values are what the caller passed. By habit this parameter is called kwargs, short for keyword arguments.

Example 2: a profile printer with **kwargs
def show_profile(**kwargs):
    for key in sorted(kwargs):
        print(key + ": " + str(kwargs[key]))

show_profile(name="Asha", age=21, city="Pune")
print("---")
show_profile(language="Python")
age: 21 city: Pune name: Asha --- language: Python

We used sorted(kwargs) so that the output order is the same every time you run the program. A dictionary does keep the order in which keys were passed, so you could also loop directly, but sorting makes examples easy to compare.

Mixing normal parameters with variable ones

You can put normal parameters first, then *args, then **kwargs. Python fills the normal parameters from the left, sends leftover positional values to *args, and sends leftover keyword values to **kwargs. The order in the definition is fixed: normal parameters, then *args, then kwargs. Writing kwargs before *args is a syntax error.

Example 3: all three together
def order(customer, *items, **options):
    print("Customer:", customer)
    print("Items:", items)
    print("Options:", options)

order("Ravi", "tea", "biscuits", sugar=False, size="large")
order("Meena")
Customer: Ravi Items: ('tea', 'biscuits') Options: {'sugar': False, 'size': 'large'} Customer: Meena Items: () Options: {}

Required first, flexible after

A good habit is to keep important values as normal parameters and use the variable parts only for the truly optional extras. For example, a average(first, *rest) function guarantees at least one number, which avoids a division by zero when the caller passes nothing. The first value is required and the rest are optional.

Example 4: average that needs at least one number
def average(first, *rest):
    numbers = (first,) + rest
    return sum(numbers) / len(numbers)

print(average(10))
print(average(10, 20, 30))
print(average(4, 5))
10.0 20.0 4.5

Rules to remember

  • *args always becomes a tuple, even if one value or no value is passed.
  • **kwargs always becomes a dictionary, even if it is empty.
  • Normal parameters come first, then *args, then **kwargs.
  • Parameters written after *args can only be given by keyword (keyword-only parameters).
  • The names args and kwargs are only conventions. The stars are what matter.
Do not overuse variable arguments. If a function really needs exactly three values, name three parameters. Clear names make code easier to read than a bag of unnamed values.

Python syntax

Syntax
def function_name(*args):
    # args is a tuple
Syntax
def function_name(**kwargs):
    # kwargs is a dict
Syntax
def function_name(a, b, *args, **kwargs):
    ...

Real-world applications

  • Logging helpers that accept any number of messages.
  • Math helpers such as sum, minimum or average of many numbers.
  • Configuration functions that accept optional settings as keywords.
  • Wrapper functions that pass all their arguments on to another function.
  • Building HTML tags or database queries from flexible options.

Common mistakes

Mistake: Writing def f(**kwargs, *args) with the double star first.
Fix: Always put *args before **kwargs in the definition.
Mistake: Expecting args to be a list and calling args.append(1).
Fix: args is a tuple and cannot change. Convert it with list(args) if you need a list.
Mistake: Dividing by len(args) without checking for an empty call.
Fix: Require a first normal parameter or test if not args before dividing.
Mistake: Passing a list as one argument and expecting it to be spread out.
Fix: Use *my_list at the call site to unpack it, which is explained in the next chapter.

Important tips

  • Use *args when the values are all the same kind of thing, such as numbers.
  • Use **kwargs when the extra values are named options.
  • Give the function a docstring that says what extra values are allowed.
  • Use sorted(kwargs) when you want stable printed output.

Key points summary

  • A star before a parameter collects extra positional arguments into a tuple.
  • Two stars collect extra keyword arguments into a dictionary.
  • The definition order is normal, *args, then **kwargs.
  • The collections can be empty when the caller passes nothing.
  • args and kwargs are only popular names.

Exam and interview points

  • *args gives a tuple and **kwargs gives a dict.
  • Parameter order: positional, *args, keyword-only, **kwargs.
  • type(args) prints <class 'tuple'>.
  • An empty *args call gives an empty tuple, not None.

Quick revision

  • *args = extra positional values in a tuple.
  • **kwargs = extra keyword values in a dict.
  • Order: normal, *args, **kwargs.
  • Both can be empty.
  • Names are only convention.

Frequently asked questions

Do I have to call the parameters args and kwargs?

No. Any valid name works, such as `*numbers` or `**options`. The names args and kwargs are a strong convention, so other programmers will understand them quickly.

Can a function have more than one *args?

No. A function can have only one star parameter and only one double-star parameter.

What happens if I pass an unexpected keyword and the function has no **kwargs?

Python raises a TypeError saying the function got an unexpected keyword argument.

Is *args slower than normal parameters?

There is a tiny cost to build the tuple, but it is almost never important. Choose the design that makes your code clearest.

Practise this chapter

15 practice questions Take the chapter quiz

Related chapters