🌱 Junior Track 09 of 09

9. *args & **kwargs & Unpacking

Master flexible function parameters: `def example(*args)` for variable positional arguments (tuples), `def example(**kwargs)` for variable keyword arguments (dictionaries), list unpacking (`print(*numbers)`), and dictionary unpacking (`function(**data)`).

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 09 — *args & **kwargs & UNPACKING OPERATORS
# ==============================================================================

# 1. Variable Positional Arguments (*args)
def example_args(*args):
    """*args gathers positional arguments into a Tuple."""
    return f"Received {len(args)} positional arguments: {args} (Type: {type(args).__name__})"

# 2. Variable Keyword Arguments (**kwargs)
def example_kwargs(**kwargs):
    """**kwargs gathers key=value arguments into a Dictionary."""
    return f"Received {len(kwargs)} keyword arguments: {kwargs} (Type: {type(kwargs).__name__})"

# 3. Target function for argument unpacking
def display_profile(name: str, age: int) -> str:
    return f"Developer: {name}, Age: {age}"

if __name__ == "__main__":
    # --- DEMO 1: *args & **kwargs Packing ---
    print(example_args(10, 20, 30))
    print(example_kwargs(role="Backend Engineer", status="Active"))

    # --- DEMO 2: Iterable Unpacking with * ---
    numbers = [1, 2, 3]
    print("Unpacked list values:", *numbers)  # Passes 1, 2, 3 as separate print arguments

    # --- DEMO 3: Dictionary Unpacking with ** ---
    data = {"name": "Dilshad", "age": 30}
    profile_info = display_profile(**data)      # Unpacks into name="Dilshad", age=30
    print(profile_info)
🌱 Junior Track 09 Master Reference

9. Python *args & **kwargs (Packing, Unpacking & Signature Rules)

1️⃣ Positional Argument Packing: `def example(*args)`

The *args syntax allows a function to accept any number of positional arguments. Inside the function body, args is bound to an immutable tuple.

def example(*args):
    for arg in args:
        print(arg)

example(1, 2, 3) # args becomes (1, 2, 3)

2️⃣ Keyword Argument Packing: `def example(**kwargs)`

The **kwargs syntax allows a function to accept arbitrary keyword arguments (key=value). Inside the function body, kwargs is bound to a standard dict.

def example(**kwargs):
    for key, value in kwargs.items():
        print(f"{key} = {value}")

example(name="Dilshad", age=30) # kwargs becomes {"name": "Dilshad", "age": 30}

3️⃣ Iterable Unpacking: `print(*numbers)`

When calling a function, prefixing a list, tuple, or generator with * unpacks its individual elements as distinct positional arguments.

numbers = [1, 2, 3]

print(*numbers) # Equivalent to print(1, 2, 3) -> Output: 1 2 3

# Also useful for merging lists:
combined = [*numbers, 4, 5] # [1, 2, 3, 4, 5]

4️⃣ Dictionary Unpacking: `function(**data)`

Prefixing a dictionary with ** unpacks its key-value pairs as keyword arguments matching function parameter names.

def greet_developer(name, age):
    print(f"Hello {name}, you are {age} years old.")

data = {"name": "Dilshad", "age": 30}
greet_developer(**data) # Equivalent to greet_developer(name="Dilshad", age=30)

# Also useful for merging dictionaries:
merged_dict = {**data, "role": "Engineer"}

5️⃣ Mandatory Parameter Ordering Rules

When combining multiple parameter types in Python function signatures, you must strictly follow this order:

def master_signature(pos1, pos2, /, default_pos=10, *args, kw_only, **kwargs):
    """ 1. Positional-only parameters (before /) 2. Standard positional/keyword parameters 3. *args variadic positional collector 4. Keyword-only parameters (after * or *args) 5. **kwargs variadic keyword collector """

⭐ Rate Track 09: *args & **kwargs (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 8. Functions 🌱 Junior Hub 10. Scope & Namespaces →