Python/Tutorial/Functions/Defining a Function with *args

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Introduction

Sometimes you want to write a function that can take an arbitrary number of non-keyword arguments. To do so, we use a special syntax to accumulate the arguments in a tuple.

Syntax

You can specify the non-keyword argument accumulator using the following syntax:

def name(*args):
    ...

Note the asterisk '*'. This means that 'args' will consume all of the remaining non-keyword arguments.

You can specify specific parameters before the non-keyword argument accumulator.

def name(a, b, c, *args):
    ...

This means that this function must have at least 3 arguments, but can have more. The first three non-keyword arguments will be assigned to a, b and c respectively. Any additional arguments will be consumed by the 'args' tuple.

Note that you need not use 'args' as the name of the parameter. You can use anything you like, as long as it isn't the name of another parameter.

Examples

In Practice

Homework