Lesson 19 / 47

*args and **kwargs

Accept any number of positional or keyword arguments.

Variable arguments

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.

def total(*args, **kwargs):
    print(args)      # (1, 2, 3)
    print(kwargs)    # {'tax': 0.1}
    return sum(args) * (1 + kwargs.get("tax", 0))

print(total(1, 2, 3, tax=0.1))

Unpacking on call

The * and ** also unpack on the call side: total(*my_list, **my_dict) spreads them out.