Args and kwargs in Python

Posted by Daksh on Sunday, April 3, 2022

Args and kwargs in Python

Args

Args are used to pass a variable number of arguments to a function. You should use *args only as a parameter name in the function definition, not elsewhere. The reason is that *args is not a keyword; it is just a conventional name. You could use *daksh or *whatever as a parameter name, but it is strongly recommended that you stick to *args.

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

print(sum_numbers(1, 2, 3, 4, 5)) # 15
print(sum_numbers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) # 55

Kwargs

Kwargs are used to pass a variable number of keyword arguments to a function. You should use **kwargs only as a parameter name in the function definition, not elsewhere. The reason is that **kwargs is not a keyword; it is just a conventional name. You could use **daksh or **whatever as a parameter name, but it is strongly recommended that you stick to **kwargs.

def order_price(**kwargs):
    total = 0
    print(kwargs)
    for commodity, price in kwargs.items():
        total += price
    return total

print(order_price(apple=5, orange=3, banana=2)) 
# output: {'apple': 5, 'orange': 3, 'banana': 2}, 10
print(order_price(apple=5, orange=3, banana=2, grapes=10)) # 20
# output: {'apple': 5, 'orange': 3, 'banana': 2, 'grapes': 10}, 20