How to Use *args and **kwargs in Python Functions

Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

20 lines
Python 3.9+
def display_info(title, *args, **kwargs):
    """Display positional and keyword arguments received."""
    print(f"Title: {title}")
    print(f"Additional positional args ({len(args)}):")
    for i, arg in enumerate(args, 1):
        print(f"  {i}. {arg}")
    print(f"Keyword args ({len(kwargs)}):")
    for key, value in kwargs.items():
        print(f"  {key} = {value}")


if __name__ == "__main__":
    display_info(
        "User Profile",
        "Alice",
        "Engineer",
        age=30,
        city="Berlin",
        active=True,
    )

Output

stdout
Title: User Profile
Additional positional args (2):
  1. Alice
  2. Engineer
Keyword args (3):
  age = 30
  city = Berlin
  active = True

How it works

The *args parameter collects any number of extra positional arguments into a tuple, while **kwargs gathers extra keyword arguments into a dictionary. Using the * and ** unpacking operators in the function signature allows you to accept a flexible number of inputs. Inside the function, args behaves like a tuple, so you can iterate over it with enumerate() to number each argument. kwargs is a normal dictionary, so you can loop through its items with .items() to access both keys and values. This pattern is especially useful for wrappers, decorators, and APIs that need to forward parameters to other functions.

Common mistakes

  • Forgetting that *args is a tuple and **kwargs is a dict, not lists or other types
  • Using *args or **kwargs after a required parameter without proper ordering
  • Assuming the variable names must be literally 'args' and 'kwargs' — they can be named anything
  • Trying to call a function with extra positional arguments when **kwargs is used instead of *args

Variations

  1. Use `def func(*args, **kwargs)` to accept everything without a required title parameter
  2. A decorator that passes through arguments using `f(*args, **kwargs)`

Real-world use cases

  • Creating a logging wrapper that accepts a message and arbitrary metadata without breaking existing callers.
  • Building a configuration loader that merges user-provided overrides with defaults via `**kwargs`.
  • Designing a function that forwards optional parameters to multiple downstream calls in an automation script.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.