Search code examples
pythonargument-unpacking

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


Solution

  • Given:

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

    Either max(mat) or max(*mat) will give the same result because the individual sublist are being compared:

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

    In the first case, max(mat), you have a iterable list of lists returning each sublist one at a time. In the second case, max(*mat), the elements (sublists) within that list of lists are unpacked into multiple individual arguments to max.

    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