A safe max() function for empty lists

PythonListExceptionError HandlingMax

Python Problem Overview


Evaluating,

max_val = max(a)

will cause the error,

ValueError: max() arg is an empty sequence

Is there a better way of safeguarding against this error other than a try, except catch?

a = []
try:
    max_val = max(a)
except ValueError:
    max_val = default 

Python Solutions


Solution 1 - Python

In Python 3.4+, you can use default keyword argument:

>>> max([], default=99)
99

In lower version, you can use or:

>>> max([] or [99])
99

NOTE: The second approach does not work for all iterables. especially for iterator that yield nothing but considered truth value.

>>> max(iter([]) or 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

Solution 2 - Python

In versions of Python older than 3.4 you can use itertools.chain() to add another value to the possibly empty sequence. This will handle any empty iterable but note that it is not precisely the same as supplying the default argument as the extra value is always included:

>>> from itertools import chain
>>> max(chain([42], []))
42

But in Python 3.4, the default is ignored if the sequence isn't empty:

>>> max([3], default=42)
3

Solution 3 - Python

The max of an empty sequence "should" be an infinitely small thing of whatever type the elements of the sequence have. Unfortunately, (1) with an empty sequence you can't tell what type the elements were meant to have and (2) there is, e.g., no such thing as the most-negative integer in Python.

So you need to help max out if you want it to do something sensible in this case. In recent versions of Python there is a default argument to max (which seems to me a misleading name, but never mind) which will be used if you pass in an empty sequence. In older versions you will just have to make sure the sequence you pass in isn't empty -- e.g., by oring it with a singleton sequence containing the value you'd like to use in that case.

[EDITED long after posting because Yaakov Belch kindly pointed out in comments that I'd written "infinitely large" where I should have written "infinitely small".]

Solution 4 - Python

Another solution could be by using ternary operators:

nums = []
max_val = max(nums) if nums else 0

or

max val = max(iter(nums) if nums else [0])

Solution 5 - Python

_DEFAULT = object()

def max_default(*args, **kwargs):
    """
    Adds support for "default" keyword argument when iterable is empty.
    Works for any iterable, any default value, and any Python version (versions >= 3.4
    support "default" parameter natively).

    Default keyword used only when iterable is empty:

    >>> max_default([], default=42)
    42

    >>> max_default([3], default=42)
    3

    All original functionality is preserved:

    >>> max_default([])
    Traceback (most recent call last):
    ValueError: max() arg is an empty sequence

    >>> max_default(3, 42)
    42
    """
    
    default = kwargs.pop('default', _DEFAULT)
    try:
        return max(*args, **kwargs)
    except ValueError:
        if default is _DEFAULT:
            raise
        return default

Bonus:

def min_default(*args, **kwargs):
    """
    Adds support for "default" keyword argument when iterable is empty.
    Works for any iterable, any default value, and any Python version (versions >= 3.4
    support "default" parameter natively).

    Default keyword used only when iterable is empty:

    >>> min_default([], default=42)
    42

    >>> min_default([3], default=42)
    3

    All original functionality is preserved:

    >>> min_default([])
    Traceback (most recent call last):
    ValueError: min() arg is an empty sequence

    >>> min_default(3, 42)
    3
    """

    default = kwargs.pop('default', _DEFAULT)
    try:
        return min(*args, **kwargs)
    except ValueError:
        if default is _DEFAULT:
            raise
        return default

Solution 6 - Python

Can create simple lambda to do this:

get_max = lambda val_list: max([ val for val in val_list if val is not None ]) if val_list else None

You can call it this way:
get_max(your_list)

Solution 7 - Python

Considering all the comments above it can be a wrapper like this:

def max_safe(*args, **kwargs):
    """
    Returns max element of an iterable.

    Adds a `default` keyword for any version of python that do not support it
    """
    if sys.version_info < (3, 4):  # `default` supported since 3.4
        if len(args) == 1:
            arg = args[0]
            if 'default' in kwargs:
                default = kwargs.pop('default')
                if not arg:
                    return default

                # https://stackoverflow.com/questions/36157995#comment59954203_36158079
                arg = list(arg)
                if not arg:
                    return default

                # if the `arg` was an iterator, it's exhausted already
                # so use a new list instead
                return max(arg, **kwargs)

    return max(*args, **kwargs)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexander McFarlaneView Question on Stackoverflow
Solution 1 - PythonfalsetruView Answer on Stackoverflow
Solution 2 - PythonDuncanView Answer on Stackoverflow
Solution 3 - PythonGareth McCaughanView Answer on Stackoverflow
Solution 4 - PythonKurohigeView Answer on Stackoverflow
Solution 5 - PythonMiloView Answer on Stackoverflow
Solution 6 - PythonZeeshanView Answer on Stackoverflow
Solution 7 - PythontsionyxView Answer on Stackoverflow