Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 37 of 70

Python *args and **kwargs for flexible functions

Write Python functions that accept any number of positional or keyword arguments with *args and **kwargs, and unpack lists and dicts into calls.

12 minFunctionsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite functions that accept any number of arguments with *args and **kwargs, and unpack a list or dictionary into a call.

After this lesson you can write a function that takes as many arguments as the caller wants, and you can unpack a list or a dictionary into a call in one step.

The problem

The built-in print accepts one value, or two, or ten. How could you write a function that behaves like that? A fixed list of parameters will not do. Python offers two special parameters for it.

*args: any number of positional arguments

A parameter whose name starts with one star collects all the extra positional arguments into a tuple.

python
def total(*prices):
    print(prices)
    return sum(prices)

print(total(10, 20, 5))
print(total())
result
(10, 20, 5)
35
()
0

Inside the function prices is an ordinary tuple, so you can loop over it, count it or pass it to sum. With no arguments it is an empty tuple. The traditional name is args, but any name works because the star does the job.

You can combine normal parameters with the star parameter. Normal ones fill first, and the rest goes to the tuple.

python
def announce(shop, *items):
    for item in items:
        print(f"{shop}: {item}")

announce("Corner Shop", "milk", "eggs")
result
Corner Shop: milk
Corner Shop: eggs

**kwargs: any number of keyword arguments

Two stars collect extra keyword arguments into a dictionary. The keys are the argument names as strings.

python
def show_details(**details):
    print(details)
    for key, value in details.items():
        print(key, "=", value)

show_details(name="Asha", course="Python", year=2)
result
{'name': 'Asha', 'course': 'Python', 'year': 2}
name = Asha
course = Python
year = 2

This is handy for functions with many optional settings, or when you want to pass options through to another function.

Using both together

The two can appear in the same definition. The order in the parameter list is: normal parameters, *args, keyword-only parameters, and **kwargs last.

python
def record(title, *tags, **info):
    print("title:", title)
    print("tags:", tags)
    print("info:", info)

record("Menu", "food", "daily", price=4, vegan=True)
result
title: Menu
tags: ('food', 'daily')
info: {'price': 4, 'vegan': True}

Unpacking at the call

The stars have a second job, at the call site. A star in front of a list or tuple spreads its items out as separate arguments. Two stars in front of a dictionary spread it out as keyword arguments.

python
def volume(length, width, height):
    return length * width * height

sizes = [2, 3, 4]
print(volume(*sizes))

box = {"length": 5, "width": 2, "height": 3}
print(volume(**box))
result
24
30

This is the reverse of collecting. It is useful when your data is already in a list or dictionary, for example rows read from a file.

You can also use the star to join sequences or print them neatly:

python
numbers = [1, 2, 3]
print(*numbers)
print(*numbers, sep=" + ")
merged = [*numbers, 4, 5]
print(merged)
result
1 2 3
1 + 2 + 3
[1, 2, 3, 4, 5]

Passing arguments through

A common real use is a small wrapper that adds behaviour and then forwards everything unchanged.

python
def loud_print(*args, **kwargs):
    print("LOG:", end=" ")
    print(*args, **kwargs)

loud_print("stock low", "tea", sep=" | ")
result
LOG: stock low | tea

The wrapper does not need to know what print accepts. It simply passes everything along. Decorators, which come later in this course, rely on exactly this pattern.

Forcing named options

A star in the parameter list is also useful on its own. Anything after *args can only be given by name. That makes a call self-explanatory, because flags like True always appear beside a label.

python
def join_words(*words, separator=" ", upper=False):
    text = separator.join(words)
    return text.upper() if upper else text

print(join_words("fresh", "bread"))
print(join_words("fresh", "bread", separator="-", upper=True))
result
fresh bread
FRESH-BREAD

Here separator and upper can never be swallowed into words by accident, since a positional argument always goes to the tuple. This design is common in library functions: a variable list of values followed by named options.

Common mistakes

  • Forgetting that args is a tuple. You cannot append to it. Convert with list(args) if you need to change it.
  • Putting a positional argument after keyword arguments in a call. Positional ones must come first.
  • Placing **kwargs before other parameters. It must be last.
  • Using a single star when you meant two. f(*box) unpacks only the dictionary keys, not the values.
  • Overusing it. If a function takes three known values, name the three parameters. Clear names beat a hidden bag of arguments.

A function that does not collect keywords rejects extra ones:

python
def volume(length, width, height):
    return length * width * height

volume(1, 2, 3, colour="red")
result
TypeError: volume() got an unexpected keyword argument 'colour'

Exercise

Write a function longest(*words) that returns the longest word it is given. If called with no words it should return an empty string. Test it with "tea", "coffee", "milk".

Show one possible answer
python
def longest(*words):
    best = ""
    for word in words:
        if len(word) > len(best):
            best = word
    return best

print(longest("tea", "coffee", "milk"))
print(repr(longest()))
result
coffee
''

Key points

  • *args collects extra positional arguments into a tuple.
  • **kwargs collects extra keyword arguments into a dictionary.
  • The names args and kwargs are only a convention. The stars are what matter.
  • At the call, *items unpacks a sequence and **options unpacks a dictionary into separate arguments.
  • In the parameter list the order is normal parameters, *args, keyword-only parameters, then **kwargs.

Check yourself

1. Inside def f(*args):, what type is args?
2. Inside def f(**kwargs):, what type is kwargs?
3. What does print(*[1, 2, 3]) do?
4. Which parameter order is valid?