Arbitrary arguments

Intermediate Python for Developers

Jasmin Ludolf

Curriculum Manager

Limitations of defined arguments

def average(values):
    """Find the mean in a sequence of values and round to two decimal places."""

    average_value = sum(values) / len(values)
    rounded_average = round(average_value, 2)
    return rounded_average

# Using six arguments print(average(15, 29, 4, 13, 11, 8))
TypeError: average() takes 1 positional argument but 6 were given
Intermediate Python for Developers

Arbitrary positional arguments

  • Docstrings help clarify how to use custom functions

  • Arbitrary arguments allow functions to accept any number of arguments

# Allow any number of positional, non-keyword arguments
def average(*args):
    # Function code remains the same
  • Conventional naming: *args

  • Allows a variety of uses while producing expected results!

Intermediate Python for Developers

Using arbitrary positional arguments

# Calling average with six positional arguments
print(average(15, 29, 4, 13, 11, 8))
13.33
Intermediate Python for Developers

Args create a single iterable

  • *: Convert arguments to a single iterable (tuple)
# Calculating across multiple lists
print(average(*[15, 29], *[4, 13], *[11, 8]))
13.33
Intermediate Python for Developers

Arbitrary keyword arguments

# Use arbitrary keyword arguments
def average(**kwargs):

average_value = sum(kwargs.values()) / len(kwargs.values()) rounded_average = round(average_value, 2) return rounded_average
  • Arbitrary keyword arguments: **kwargs

  • keyword=value

Intermediate Python for Developers

Using arbitrary keyword arguments

# Calling average with six kwargs
print(average(a=15, b=29, c=4, d=13, e=11, f=8))
13.33
# Calling average with one kwarg
print(average(**{"a":15, "b":29, "c":4, "d":13, "e":11, "f":8}))
13.33
  • Each key-value pair in the dictionary is mapped to a keyword argument and value!
Intermediate Python for Developers

Kwargs create a single iterable

# Calling average with three kwargs
print(average(**{"a":15, "b":29}, **{"c":4, "d":13}, **{"e":11, "f":8}))
13.33
Intermediate Python for Developers

Let's practice!

Intermediate Python for Developers

Preparing Video For Download...