Back to Python Notes
Topic #223

*args and **kwargs

Learn how to write Python functions that accept any number of positional and keyword arguments using *args and **kwargs.

What it is

In Python, *args and **kwargs are special syntax used in function definitions to pass a variable number of arguments. The names args and kwargs are conventions; the asterisks (*) and double asterisks (**) are what matter.

  • *args: Collects extra positional arguments into a tuple.
  • **kwargs: Collects extra keyword arguments into a dictionary.

This allows functions to be flexible without hardcoding specific parameter counts or names.

Why it matters

  • Wrapper Functions: Essential for decorators that need to pass through unknown arguments to the wrapped function.
  • API Clients: Useful when building interfaces where users might want to pass arbitrary query parameters or headers.
  • Configuration: Allows setting default values while accepting overrides via keywords.
  • Extensibility: Future-proofing functions so they can handle new argument types without breaking existing calls.

Syntax or steps

The order of parameters in a function definition must follow this sequence:

  1. Standard positional arguments
  2. *args (if present)
  3. Keyword-only arguments (optional)
  4. **kwargs (if present)

Inside the function body, args behaves like a tuple, and kwargs behaves like a dictionary.

Example

def log_event(event_type, *details, **metadata):
    print(f"Event: {event_type}")
    
    # Process positional details (tuple)
    if details:
        print("Details:", ", ".join(details))
        
    # Process keyword metadata (dictionary)
    if metadata:
        for key, value in metadata.items():
            print(f"  {key}: {value}")

# Calling the function
log_event(
    "UserLogin", 
    "IP:192.168.1.1", 
    "Device:Mobile", 
    user_id=101, 
    status="success"
)

Explanation:

  • "UserLogin" is assigned to the standard parameter event_type.
  • "IP:192.168.1.1" and "Device:Mobile" are collected into the details tuple.
  • user_id=101 and status="success" are collected into the metadata dictionary.

Common mistakes

  • Misunderstanding Types: Remember args is a tuple (immutable, ordered), not a list. You cannot append to it directly inside the function.
  • Ordering Errors: Placing **kwargs before *args causes a SyntaxError. *args must come before **kwargs.
  • Unpacking Confusion: When calling a function, *list unpacks a list into positional args, and **dict unpacks a dict into keyword args. Do not confuse definition syntax with call syntax.
  • Overusing Flexibility: If you know exactly which arguments are needed, use explicit named parameters. It improves code readability and IDE support.

When to use it

Compare *args/**kwargs with explicit parameters:

ScenarioRecommended Approach
Fixed number of known inputs Explicit parameters (e.g., def add(a, b))
Decorators or wrappers *args, **kwargs
Aggregating data (e.g., summing numbers) *args
Passing options to underlying libraries **kwargs

Practice

Guided Exercise: Write a function called create_profile that takes a required name, collects any additional strings into a tuple called skills, and collects any keyword arguments into a dictionary called preferences. Print all three.

Challenge: Modify the function to calculate the average of all numeric values passed in *args, ignoring non-numeric types.

Hint for Challenge: Use isinstance(arg, (int, float)) to filter the tuple before calculating.

Quick check

Question: What data type does **kwargs collect arguments into?

Answer: A dictionary.

Summary

*args and **kwargs provide essential flexibility for Python functions by capturing variable-length positional and keyword arguments as tuples and dictionaries, respectively. They are critical for writing robust decorators, wrappers, and APIs but should be used judiciously to maintain code clarity.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

*args and **kwargs – FAQs

Quick answers about learning *args and **kwargs in Python.

This free note from Coding Now Tech Institute explains *args and **kwargs in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including *args and **kwargs, is 100% free with no signup required.
With focused practice, most students grasp *args and **kwargs in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now