Notes
Categories

*args and **kwargs in Python [ English ]

< Prev Next >

1. Introduction

In Python, functions often need to handle a variable number of arguments. The special symbols *args and **kwargs allow functions to accept an arbitrary number of inputs, making them more flexible and reusable.

These constructs are particularly useful when the exact number of arguments is not known in advance.


2. Definition


3. Understanding *args

*args collects extra positional arguments into a tuple.

Syntax:

def function_name(*args):
    # code

Example:

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

print(add_numbers(1, 2, 3))
print(add_numbers(5, 10, 15, 20))

Output:

6
50

Here, args behaves like a tuple:

(1, 2, 3)

4. Understanding **kwargs

**kwargs collects extra keyword arguments into a dictionary.

Syntax:

def function_name(**kwargs):
    # code

Example:

def display_info(**kwargs):
    for key, value in kwargs.items():
        print(key, ":", value)

display_info(name="Alice", age=25, city="Delhi")

Output:

name : Alice
age : 25
city : Delhi

Here, kwargs behaves like:

{'name': 'Alice', 'age': 25, 'city': 'Delhi'}

5. Using *args and **kwargs Together

You can use both in the same function.

def demo(a, *args, **kwargs):
    print("a =", a)
    print("args =", args)
    print("kwargs =", kwargs)

demo(10, 20, 30, name="John", age=22)

Output:

a = 10
args = (20, 30)
kwargs = {'name': 'John', 'age': 22}

6. Order of Parameters

When combining different types of parameters, the correct order must be followed:

def func(a, b, *args, **kwargs):
    pass

Order:

  1. Normal parameters
  2. *args
  3. **kwargs

7. Practical Use Cases


8. Key Differences

Feature *args **kwargs
Type Tuple Dictionary
Arguments Positional Keyword
Usage Multiple values Named parameters

9. Key Insight

*args and **kwargs are not special keywords—the names can be anything. The important part is the * and ** operators. However, using the conventional names improves readability and is considered best practice.


10. Conclusion

*args and **kwargs provide powerful mechanisms for handling variable inputs in Python functions. They enhance flexibility, reduce code redundancy, and are widely used in advanced Python programming and real-world applications.

< Prev Next >