9.3. Idiom Max

  • max(iterable, *, key=None)

  • max(iterable, *, default, key=None)

  • max(arg1, arg2, *args, key=None)

  • With a single iterable argument, return its biggest item

  • The default keyword-only argument specifies an object to return if the provided iterable is empty

  • With two or more positional arguments, return the largest argument

Return the largest item in an iterable or the largest of two or more arguments.

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.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised. [1]

9.3.1. Iterable

>>> data = [1, 2, 3]
>>> max(data)
3
>>> max([1, 2, 3])
3
>>> max(1, 2, 3)
3

9.3.2. Default

  • When iterable is empty

>>> data = []
>>> max(data)
Traceback (most recent call last):
ValueError: max() iterable argument is empty
>>> max(data, default=0)
0
>>> result = max(data, default=None)
>>> print(result)
None

9.3.3. Key

>>> USERS = [
...     {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
...     {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
...     {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
...     {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
...     {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
...     {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
... ]

Find the oldest person:

>>> def age(user):
...     return user['age']
>>>
>>> result = max(USERS, key=age)
>>>
>>> print(result)
{'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34}

9.3.4. Use Case - 1

>>> USERS = [
...     ('firstname', 'lastname', 'age'),
...     ('Alice', 'Apricot', 30),
...     ('Bob', 'Blackthorn', 31),
...     ('Carol', 'Corn', 32),
...     ('Dave', 'Durian', 33),
...     ('Eve', 'Elderberry', 34),
...     ('Mallory', 'Melon', 15),
... ]

Find the youngest person:

>>> def age(user):
...     return user[2]
>>>
>>> result = max(USERS[1:], key=age)
>>>
>>> print(result)
('Eve', 'Elderberry', 34)

9.3.5. References

9.3.6. Assignments

# %% About
# - Name: Idiom Max Sequence
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define variable `result: int` with the greatest value from `DATA`
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj zmienną `result: int` z największą wartością z `DATA`
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `max()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> result
3
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result: int

# %% Data
DATA = [1, 2, 3]

# %% Result
result = ...

# %% About
# - Name: Idiom Max Default
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define variable `result: int` with the greatest value from `DATA`
# 2. Return `None` if `DATA` is empty
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj zmienną `result: int` z największą wartością z `DATA`
# 2. Zwróć `None`, jeśli `DATA` jest puste
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `max()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> result is None
True
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result: int

# %% Data
DATA = []

# %% Result
result = ...

# %% About
# - Name: Idiom Max Key
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define variable `result: tuple` with the oldest user from `DATA`
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj zmienną `result: tuple` z najstarszym użytkownikiem z `DATA`
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# ('Eve', 'Elderberry', 34)

# %% Hints
# - `max()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> result
('Eve', 'Elderberry', 34)
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result: int

# %% Data
DATA = [
    ('firstname', 'lastname', 'age'),
    ('Alice', 'Apricot', 30),
    ('Bob', 'Blackthorn', 31),
    ('Carol', 'Corn', 32),
    ('Dave', 'Durian', 33),
    ('Eve', 'Elderberry', 34),
    ('Mallory', 'Melon', 15),
]

# %% Result
result = ...

# %% About
# - Name: Idiom Max Sequence
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define variable `result: int` with the greatest numerical value from `DATA`
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj zmienną `result: int` z największą wartością numeryczną z `DATA`
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# 7.6

# %% Hints
# - `max()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> result
7.6
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result: int

# %% Data
DATA = [
    ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
    (5.8, 2.7, 5.1, 1.9, 'virginica'),
    (5.1, 3.5, 1.4, 0.2, 'setosa'),
    (5.7, 2.8, 4.1, 1.3, 'versicolor'),
    (6.3, 2.9, 5.6, 1.8, 'virginica'),
    (6.4, 3.2, 4.5, 1.5, 'versicolor'),
    (4.7, 3.2, 1.3, 0.2, 'setosa'),
    (7.0, 3.2, 4.7, 1.4, 'versicolor'),
    (7.6, 3.0, 6.6, 2.1, 'virginica'),
    (4.9, 3.0, 1.4, 0.2, 'setosa'),
    (4.9, 2.5, 4.5, 1.7, 'virginica'),
]

# %% Result
result = ...

# %% About
# - Name: Idiom Max Implementation
# - Difficulty: medium
# - Lines: 5
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Write own implementation of a built-in `max()` function
# 2. Define function `mymax` with
#    parameter `iterable: list[int|float]`
#    return `int|float`
# 3. Don't validate arguments and assume, that user will
#    always pass valid type of arguments
# 4. Do not use built-in function `max()`
# 5. Run doctests - all must succeed

# %% Polish
# 1. Zaimplementuj własne rozwiązanie wbudowanej funkcji `max()`
# 2. Zdefiniuj funkcję `mymax` z parametrami:
#    parametr `iterable: list[int|float]`
#    return `int|float`
# 3. Nie waliduj argumentów i przyjmij, że użytkownik:
#    zawsze poda argumenty poprawnych typów
# 4. Nie używaj wbudowanej funkcji `max()`
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# mymax([1]) == 1
# mymax([0]) == 0
# mymax([1, 0, 2]) == 2
# mymax([-1, 2, 0]) == 2
# mymax([0, 0, 0]) == 0

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction
>>> assert isfunction(mymax)

>>> mymax([1])
1

>>> mymax([0])
0

>>> mymax([1, 0, 2])
2

>>> mymax([-1, 2, 0])
2

>>> mymax([0, 0, 0])
0
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
mymax: Callable[[list[int|float]], int|float]

# %% Data

# %% Result
def mymax(iterable):
    ...