Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does max(*list) and max(list) do the same thing in python?

See below example:

>>>f = [[1],[2],[3]]
>>>max(f)
Out[21]: [3]
>>>max(*f)
Out[22]: [3]

The unpack operator did not have an effect here, I am trying to unpack a list and get a maximal value of matrix(two dim list).

like image 444
Pythoner Avatar asked Dec 03 '22 11:12

Pythoner


1 Answers

The documentation for max mentions:

builtin max

max(iterable, *[, key, default])

max(arg1, arg2, *args[, key])

...

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

In the first case you have one positional argument, in the second case you have multiple.


To get what you want, which is the maximal entry in a matrix you could try

max(entry for row in matrix for entry in row)

This will pass one argument to the max function which is a generator that iterates over all the entries in the matrix - triggering the first case which finds the maximum of an iterable.

like image 136
WorldSEnder Avatar answered Dec 19 '22 21:12

WorldSEnder