Login
You're viewing the code4lib.social public feed.
  • Nov 26, 2026, 9:01 PM

    Python Tip #330 (of 365):

    Pass a default to max and min to handle empty iterables.

    The max and min functions raise an exception when given nothing to compare:

    >>> numbers = []
    >>> max(numbers)
    Traceback (most recent call last):
    ...
    ValueError: max() iterable argument is empty

    🧵 (1/3)

    #Python #DailyPythonTip

    💬 1🔄 1⭐ 0

Replies

  • Nov 26, 2026, 9:01 PM

    You could catch that ValueError:
    def numeric_range(numbers):
    try:
    return max(numbers) - min(numbers)
    except ValueError:
    return 0

    But it's simpler to pass a default instead:
    def numeric_range(numbers):
    return max(numbers, default=0) - min(numbers, default=0)

    That default value will be returned if an empty iterable is given.

    🧵 (2/3)

    💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0