CodeBlanks Logo Icon CodeBlanks

*args and **kwargs

Learn flexible parameters with *args and **kwargs.

Variable arguments with *args

With *args you can send any number of positional arguments to a function; they are collected into a tuple:

def total(*args):
    return sum(args)

print(total(1, 2, 3))   # 6
print(total(10, 20))    # 30

The star makes the incoming values collect into a single tuple. This makes the function flexible.

Keyword arguments with **kwargs

With **kwargs, arguments passed as keywords are collected into a dict:

def show(**kwargs):
    for k, v in kwargs.items():
        print(k, v)

show(name="Alex", age=28)

The double star makes the incoming keyword pairs collect into a dictionary. This is handy for optional settings.

*args and **kwargs can be used together; *args first, then **kwargs.

Practice Write a total function with *args

Define a function called total that takes *args and returns sum(args). Assign total(1, 2, 3) to result. Then print print(result).

Starter code

main.py
# Define the total function

Sample solution

main.py
def total(*args):
    return sum(args)
result = total(1, 2, 3)
print(result)

Expected output

6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the *args parameter

Question
def total(____):
    return sum(args)
Answer
def total(*args):
    return sum(args)

Explanation: *args collects variable arguments into a tuple.

2 What type does *args appear as inside the function?

  • Tuple Correct answer
  • List
  • Dict
  • Set

Explanation: *args values are collected into a tuple.

3 Match args and kwargs types

Term Meaning
*args Tuple
**kwargs Dict
star Collection sign
double star Dict collection

All lessons in Beginner