Variable Argument Lists

Learn about Python's dynamic function argument capabilities for tasks like web page downloading and flexible configuration options.

Overview

Default values alone do not allow us all the flexibility we might want. One thing that makes Python really slick is the ability to write methods that accept an arbitrary number of positional or keyword arguments without explicitly naming them. We can also pass arbitrary lists and dictionaries into such functions. In other languages, these are sometimes called variadic arguments, varargs.

Examples

For example, we could write a function to accept a link or list of URLs and download the web pages. The idea is to avoid the confusing-looking overhead of a singleton list when we only want one page downloaded. Instead of accepting a single value with a list of URLs, we can accept an arbitrary number of arguments, where each argument is a URL. We do this by defining one positional parameter to receive all the argument values. This parameter has to be last (among the positional parameters), and we’ll decorate it with a * in the function definition as follows:

Get hands-on with 1200+ tech skills courses.