Using *args in a Function Definition

#1
``````def biggest_number(*args):
print max(args)
return max(args)

def smallest_number(*args):
print min(args)
return min(args)
``````

Why do we need a star before the argument in these first two functions? When I take them away, the program doesn’t work…why?

Where can I find a list of all available built-in functions Python has?
#2

Hi @jjhiggins97,

In the Functions: On Beyond Strings exercise, The following statements each pass four arguments to the `biggest_number` and `smallest_number` functions:

``````biggest_number(-10, -5, 5, 10)
smallest_number(-10, -5, 5, 10)
``````

In fact, those two functions are designed to accept an arbitrary number of arguments, provided that at least one is passed. The `*` character that precedes the name `args` within the parameter specifications in the headers of those functions causes whatever arguments are passed to them to be collected into a tuple named `args`. The tuple can then be passed to the `min` or the `max` built-in functions.

If the `*` is removed, then only one argument can be passed to the `biggest_number` and `smallest_number` functions, and the calls that specify multiple arguments that are given in the program will fail. While the `max` and `min` built-in functions can be passed either sequences or one or more arguments that can be compared, the `biggest_number` and `smallest_number` functions are designed specifically for arbitrary numbers of comparable arguments.

Edited on February 5, 2019 to clarify the discussion within the final paragraph

#3

*args it means you can take multiple argument in a function

#4

Ah okay, so it stops you having to put multiple arguments in when defining the function. In other words, it allows you to pass in as many as you want?

#5

Yes, when you call the function, you can pass it as many arguments as you want. That includes calling it with no arguments. Therefore, for each function you write using this technique, consider special cases that may arise. For instance, if you call the `biggest_number` or `smallest_number` function with no arguments, it will raise an error, as exemplified here:

``````biggest_number()
``````

The console reports this problem:

``````Traceback (most recent call last):
File "/Users/glennrichard/Documents/maxmin.py", line 18, in <module>
biggest_number()
File "/Users/glennrichard/Documents/maxmin.py", line 2, in biggest_number
print(max(args))
ValueError: max() arg is an empty sequence
``````

That is because the built-in `max` function fails if you pass it an empty `list` or `tuple`. The same applies to `min`.

#6

Okay cool. Thanks a lot!