🎓 A1Learner
🔍
0 of 116 lessons completed

Python Arbitrary Arguments

Arbitrary arguments let a function collect a changing number of values from one call.

A new function for each count

A fixed parameter list needs a new function for each count.

def add_two(a, b):
    return a + b

def add_three(a, b, c):
    return a + b + c

print(add_two(1, 2))
print(add_three(1, 2, 3))

Collect with *args

The star collects every positional value. len() then counts the collected values.

def show_all(*items):
    print(len(items))

show_all("pen", "cup", "book")

Loop over *args

The collected tuple works in a for loop. Each round gives one value.

def list_items(*items):
    for item in items:
        print(item)

list_items("pen", "cup")

Collect with **kwargs

The two stars collect named values into a dict. The .get() method reads one value by its key.

def show_player(**info):
    print(info.get("name"))

show_player(name="Ana", team="Red")

Loop over **kwargs

Looping a dict gives its keys. The .get() method then reads each value.

def show_info(**info):
    for key in info:
        print(key, info.get(key))

show_info(name="Ana", age=12)

Example

def total(*numbers):
    result = 0
    for number in numbers:
        result += number
    print(result)

def show_player(**info):
    print(info.get("name"))
    print(info.get("team"))

total(2, 3, 5)
total(10, 20)
show_player(name="Ana", team="Red")

Key points

  • Use *args to collect extra positional values into a tuple
  • Tuple: a fixed group of values in order, pictured in earlier lessons
  • Use **kwargs to collect extra named values into a dict
  • Dict: a group of key and value pairs, pictured in earlier lessons

In this example, total collects its numbers with *numbers. The loop adds each number into result. The first call totals 2, 3, and 5, so it prints 10. The second call totals 10 and 20, so it prints 30. Next, show_player collects named values with **info. It reads the name and team values with .get() and prints them.

Note

The names args and kwargs are a strong habit, not a rule.

The stars do the real work.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does *args collect its values into?