Parameters in python built-in min () and sorted () functions

I am doing tasks at py.checkio.org, I come across an exercise to write my own function min()

and max()

.

I read the documentation about this function in the official documentation and I am surprised at the parameters described, they look like this:min(iterable, *[, key, default])

I'm wondering what this construction means *[,

, it's strange because it's *args

both **kwargs

understandable and also [,arg]

understandable. But *[,

very strange, what does this parameter mean?

PS the sorted () function has a strange asterisk parameter: sorted(... *, ...)

what does this mean?

+3


source to share


2 answers


The following is specific to Python 3 (which the OP is tied to).


A single star ( *

) in a function definition sorted

means that all of the following named parameters must be specified as keyword arguments ("keyword-only arguments", see PEP 3102 ). This means that the following will not work:

>>> sorted([1, 2, 3], lambda x: x)
[...]
TypeError: must use keyword argument for key function

      



Instead, you must provide these parameters using keyword arguments:

>>> sorted([1, 2, 3], key=lambda x: x)
[1, 2, 3]

      


I'm not entirely sure what the syntax is , *[, key, default]

supposed to mean (this is not valid Python, but the purpose of the document), but I think the developers want to express the same, namely that you have to provide those parameters as keyword arguments (because min

both max

can take an arbitrary number of positional arguments, which is the only way to do this).

+3


source


The part is [, key, default]

not Python syntax, it is the general grammar syntax of programming languages, denoting optional parts (optional arguments here).



EDIT: Part *

is explained in a_guest's answer (nb: this is for Python 3 only)

+3


source







All Articles