Published on

14. *args and **kwargs in Python

Authors

14. In a function, what is the meaning of *args and **kwargs?

In Python, *args and **kwargs are used in function definitions to allow the function to accept a variable number of arguments.


🔹 *argsPositional Arguments

  • Collects any extra positional arguments passed to the function.
  • Inside the function, args is a tuple.

✅ Example:

def greet(*args):
    for name in args:
        print(f"Hello, {name}!")

greet("Alice", "Bob", "Charlie")
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!

🔸 **kwargsKeyword Arguments

  • Collects any extra keyword arguments.
  • Inside the function, kwargs is a dictionary.

✅ Example:

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

print_info(name="Alice", age=30, city="Berlin")
# Output:
# name: Alice
# age: 30
# city: Berlin

🧩 You Can Combine Them:

def show_all(a, *args, **kwargs):
    print("a:", a)
    print("args:", args)
    print("kwargs:", kwargs)

show_all(1, 2, 3, x=10, y=20)
# Output:
# a: 1
# args: (2, 3)
# kwargs: {'x': 10, 'y': 20}

✅ Summary Table:

SyntaxTypeCollected AsUse Case
*argsPositionaltupleVariable number of positional arguments
**kwargsKeyworddictVariable number of keyword arguments