xplain the difference between *args and **kwargs.

Both *args and **kwargs allow functions to accept a variable number of arguments, but they serve different purposes:

Feature*args**kwargs
PurposeAccepts positional arguments as a tupleAccepts keyword arguments as a dictionary
SyntaxSingle asterisk (*args)Double asterisk (**kwargs)
Use CaseWhen you don’t know how many positional arguments will be passedWhen you don’t know how many keyword arguments will be passed
Exampledef func(*args):def func(**kwargs):


1. *args (Variable-Length Positional Arguments)

  • Collects extra positional arguments into a tuple.

  • Useful when the number of arguments is unknown.

Example:

python
def sum_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

print(sum_numbers(1, 2, 3))  # Output: 6
print(sum_numbers(10, 20))    # Output: 30

How It Works:

  • sum_numbers(1, 2, 3) → args = (1, 2, 3)

  • sum_numbers(10, 20) → args = (10, 20)


2. **kwargs (Variable-Length Keyword Arguments)

  • Collects extra keyword arguments into a dictionary.

  • Useful when passing named arguments dynamically.

Example:

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

print_user_details(name="Alice", age=25, city="New York")

Output:

text
name: Alice
age: 25
city: New York

How It Works:

  • print_user_details(name="Alice", age=25) → kwargs = {"name": "Alice", "age": 25}


Combining *args and **kwargs

You can use both in the same function:

python
def example_function(arg1, *args, **kwargs):
    print(f"First argument: {arg1}")
    print(f"Additional positional args: {args}")
    print(f"Keyword args: {kwargs}")

example_function(10, 20, 30, name="Alice", age=25)

Output:

text
First argument: 10
Additional positional args: (20, 30)
Keyword args: {'name': 'Alice', 'age': 25}


Key Takeaways

  • *args → Handles extra positional arguments (stored as a tuple).

  • **kwargs → Handles extra keyword arguments (stored as a dictionary).

  • Both make functions flexible for different input scenarios.

  • They are often used in decorators, inheritance, and dynamic function calls.

Would you like a practical example (e.g., building a dynamic SQL query)? 

To Top