⭐

How to Use *args and **kwargs in Python

PythonIntermediate

Accept variable arguments in functions.

Code Example

Python
# *args - variable positional arguments
def sum_all(*args):
    return sum(args)

print(f"Sum: {sum_all(1, 2, 3, 4, 5)}")

# **kwargs - variable keyword arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print("\nInfo:")
print_info(name="Alice", age=30, city="NYC")

# Combining both
def mixed_func(required, *args, **kwargs):
    print(f"Required: {required}")
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

print("\nMixed:")
mixed_func("Hello", 1, 2, 3, name="Alice", age=30)

# Practical example
def create_user(name, age, **kwargs):
    user = {"name": name, "age": age}
    user.update(kwargs)
    return user

user = create_user("Alice", 30, email="alice@example.com", city="NYC")
print(f"\nUser: {user}")

# Unpacking arguments
def greet(greeting, name):
    print(f"{greeting}, {name}!")

args = ["Hello", "Alice"]
greet(*args)

kwargs = {"greeting": "Hi", "name": "Bob"}
greet(**kwargs)

Explanation

*args collects positional arguments as tuple. **kwargs collects keyword arguments as dict. Use to create flexible functions.

Related Tutorials