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

  • A+
Category:Languages

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).

 


Given:

mat=[     [1, 2, 3],     [4, 5, 6],     [0, 9, 10] ] 

Either max(mat) or max(*mat) will give the same result:

>>> max(mat) [4, 5, 6] >>> max(*mat) [4, 5, 6] 

Since the individual sublist are being compared. (Once because your have a iterable list of lists and the other because you have fed multiple individual lists by unpacking the list of lists)

If you want the sublist that has the max value in it, use max as a key function:

>>> max(mat, key=max) [0, 9, 10] 

If you want the individual max value in a two dimensional matrix, you can flatten it:

>>> max(v for sl in mat for v in sl) 10 

Or have three max's:

>>> max(max(mat,key=max)) 10 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: