Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 5 · Flexible Arguments: *args and kwargs

Flexible Arguments: *args and **kwargs

On this pageUsing *args for Multiple Positional ArgumentsUsing **kwargs for Keyword ArgumentsCombining *args and **kwargsMini Project — Student Record Formatter

Sometimes, you may not know in advance how many arguments a function will receive.

Python provides two special tools —*args and **kwargs — that allow functions to handle a variable number of inputs gracefully.

A positional argument is matched by its position in a call; a keyword argument is passed as name=value. The names args and kwargs are conventions; the * and ** provide the behavior.

Using *args for Multiple Positional Arguments

The *args syntax lets a function accept any number of positional arguments.

Inside the function, all the extra values are stored together in a tuple.

The built-in sum() adds the numbers in a collection; an empty collection has a sum of zero. Let’s use it in a function.

def add_numbers(*args):
    print("Received:", args)
    print("Sum:", sum(args))
Listing 206 — Using *args for Multiple Positional Arguments

When you call the function, you can pass as many numbers as you want:

add_numbers(2, 4, 6)
add_numbers(5, 10, 15, 20)
Listing 207 — Using *args for Multiple Positional Arguments

Output

Received: (2, 4, 6)
Sum: 12
Received: (5, 10, 15, 20)
Sum: 50

Here,*args collects all arguments into a tuple named args, allowing the function to handle flexible input lengths.

Using **kwargs for Keyword Arguments

While *args gathers unnamed (positional) values,**kwargs collects named arguments into a dictionary.

This is useful when you want to handle labeled information.

def describe_person(**kwargs):
    print("Person details:")
    for key, value in kwargs.items():
        print(f"{key}: {value}")
Listing 208 — Using **kwargs for Keyword Arguments

You can now call the function with any combination of keyword arguments:

describe_person(name="Alice", age=28, city="Paris")

describe_person(name="Bob", job="Engineer")
Listing 209 — Using **kwargs for Keyword Arguments

Output

Person details:
name: Alice
age: 28
city: Paris
Person details:
name: Bob
job: Engineer

Each argument becomes a key–value pair inside the kwargs dictionary, giving you full flexibility to pass variable information.

Combining *args and **kwargs

You can even use both in the same function to handle any number of positional and keyword arguments together.

This makes your functions adaptable to many scenarios.

def show_info(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)
Listing 210 — Combining *args and **kwargs
show_info("Python", "Data Science", version=3.12, difficulty="Intermediate")
Listing 211 — Combining *args and **kwargs

Output

Positional arguments: ('Python', 'Data Science')
Keyword arguments: {'version': 3.12, 'difficulty': 'Intermediate'}

This combination is powerful when building reusable functions that must handle both kinds of data flexibly.

Mini Project — Student Record Formatter

Write a program that collects information about students using flexible arguments.

The function should accept any number of names and shared details (like course or year) and print them neatly. In ", ".join(names), the separator joins the strings in names into one string. These details describe the group, not a separate record for each student.

def student_info(*names, **details):
    print("Students:", ", ".join(names))
    print("Details:")
    for key, value in details.items():
        print(f"  {key}: {value}")

student_info("Alice", "Bob", "Clara", course="Python", year=2025, instructor="Dr. Smith")
Listing 212 — Mini Project — Student Record Formatter

Output

Students: Alice, Bob, Clara
Details:
  course: Python
  year: 2025
  instructor: Dr. Smith

This small project demonstrates how *args and **kwargs let functions adapt to changing requirements — an essential skill in writing flexible and professional Python programs.