What do a single star (args) and double star (kwargs) mean in Python?

In Python, you can create functions that accept a wide variety of parameters.

Single Star

The single-star (*) allows you to accept a varying number of positional arguments:

def get_name(*args):
    print('{0} {1} {2}'.format(args[0], args[1], args[2]))

get_name('John', 'A', 'Doe')

The output of running the code above is:

John A Doe

In the get_name function, args will be a tuple containing the values you passed into the function.

Double Star

The double-star (**) allows you to accept a varying number of keyword arguments (with a name and value) into a dictionary:

def get_name(**kwargs):
    print(kwargs['first'], kwargs['middle'], kwargs['last'])

get_name(first='John', last='Doe', middle='A')

The output of running the code is:

John A Doe

Helpful Links

How can I pass optional or keyword parameters from one function to another? StackOverflow: *args and **kwargs?


Leave a comment

What color are brown eyes? (spam prevention)
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.