Short answer: Use a star to collect the arguments in a tuple and then add a special case for a tuple of length one to handle a single iterable argument.

Source material: The C code that handles the logic can be found at: https://github.com/python/cpython/blob/da20d7401de97b425897d3069f71f77b039eb16f/Python/bltinmodule.c#L1708

Simplified pure python code: If you ignore the default and key keyword arguments, what's left simplifies to:

def mymax(*args):
    if len(args) == 0:
        raise TypeError('max expected at least 1 argument, got 0')
    if len(args) == 1:
        args = tuple(args[0])
    largest = args[0]
    for x in args[1:]:
        if x > largest:
            largest = x
    return largest

There are other nuances, but this should get you started.

Documentation: The special handling for the length one case versus other cases is documented here:

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.

More complete version: This includes some of aforementioned nuances like the key and default keyword arguments and the use of iterators instead of slices:

sentinel = object()

def mymax(*args, default=sentinel, key=None):
    """max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    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 arguments, return the largest argument.
    """
    if not args:
        raise TypeError('max expected at least 1 argument, got 0') 
    if len(args) == 1:
        it = iter(args[0])
    else:
        if default is not sentinel:
            raise TypeError('Cannot specify a default for max() with multiple positional arguments')
        it = iter(args)
    largest = next(it, sentinel)
    if largest is sentinel:
        if default is not sentinel:
            return default
        raise ValueError('max() arg is an empty sequence')
    if key is None:
        for x in it:
            if x > largest:
                largest = x
        return largest
    largest_key = key(largest)
    for x in it:
        kx = key(x)
        if kx > largest_key:
            largest = x
            largest_key = kx
    return largest

# This makes the tooltips nicer
# but isn't how the C code actually works
# and it is only half correct.
mymax.__text_signature__ = '($iterable, /, *, default=obj, key=func)'
Answer from Raymond Hettinger on Stack Overflow
🌐
GitHub
gist.github.com › yvan-sraka › 52384523a92bb0910d770f0fdde59bbd
Max function implementation explained in Python - Gist - GitHub
def max(list): if list[1:]: if list[0] > max(list[1:]): return list[0] else: return max(list[1:]) elif not list: return else: return list[0] ... The above function is calling the recursion twice for the same operation.
Top answer
1 of 1
46

Short answer: Use a star to collect the arguments in a tuple and then add a special case for a tuple of length one to handle a single iterable argument.

Source material: The C code that handles the logic can be found at: https://github.com/python/cpython/blob/da20d7401de97b425897d3069f71f77b039eb16f/Python/bltinmodule.c#L1708

Simplified pure python code: If you ignore the default and key keyword arguments, what's left simplifies to:

def mymax(*args):
    if len(args) == 0:
        raise TypeError('max expected at least 1 argument, got 0')
    if len(args) == 1:
        args = tuple(args[0])
    largest = args[0]
    for x in args[1:]:
        if x > largest:
            largest = x
    return largest

There are other nuances, but this should get you started.

Documentation: The special handling for the length one case versus other cases is documented here:

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.

More complete version: This includes some of aforementioned nuances like the key and default keyword arguments and the use of iterators instead of slices:

sentinel = object()

def mymax(*args, default=sentinel, key=None):
    """max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    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 arguments, return the largest argument.
    """
    if not args:
        raise TypeError('max expected at least 1 argument, got 0') 
    if len(args) == 1:
        it = iter(args[0])
    else:
        if default is not sentinel:
            raise TypeError('Cannot specify a default for max() with multiple positional arguments')
        it = iter(args)
    largest = next(it, sentinel)
    if largest is sentinel:
        if default is not sentinel:
            return default
        raise ValueError('max() arg is an empty sequence')
    if key is None:
        for x in it:
            if x > largest:
                largest = x
        return largest
    largest_key = key(largest)
    for x in it:
        kx = key(x)
        if kx > largest_key:
            largest = x
            largest_key = kx
    return largest

# This makes the tooltips nicer
# but isn't how the C code actually works
# and it is only half correct.
mymax.__text_signature__ = '($iterable, /, *, default=obj, key=func)'
Discussions

Question about max function in numpy source code, saving O(100) nanoseconds by assigning a function

Yes, big O is used here in its loose sense, meaning "bounded by".

And yes, assigning to a variable takes (a small amount of) time. But the other thing that takes time is looking up names. If you're calling um.maximum.reduce, Python needs to find um in the local namespace, then find maximum in the namespace of um, and then find reduce in the namespace of maximum. Each of those steps takes (again, a small amount of) time. Whereas once you've assigned it to a local variable, you'd only need one lookup to find it.

So if you're calling a function repeatedly in a very time-constrained environment, it will certainly be cheaper to assign it once to a local variable and call that rather than incurring the repeated cost of the two extra lookups each time.

More on reddit.com
🌐 r/learnpython
4
0
May 6, 2023
Writing my own min function?
This is the nearly same implementation of built-in min in pure Python: def min(*args, **kwargs): if not args: raise TypeError('min expected 1 arguments, got 0') elif len(args) == 1: iterable = iter(args[0]) else: iterable = args key = None for k, v in kwargs.iteritems(): if k != 'key': raise TypeError('min() got an unexpected keyword argument') elif not callable(v): raise TypeError(str(type(v).__name__) + ' object is not callable') key = v first = True for item in iterable: if key is None: val = item else: val = key(item) if first or minval > val: minval = val minitem = item first = False if first: raise ValueError('min() arg got an empty sequence') return minitem See CPython’s implementation also. More on reddit.com
🌐 r/Python
14
6
October 11, 2011
How long should a .py file be?
Generally, I don't care about the line count of a module. I group my classes / functions in a way that seems natural. Some modules are only 50 lines long. Others reach the 1000. After all, what difference does pure line count make once it's beyond "more than a couple of screens full"? More on reddit.com
🌐 r/Python
33
13
July 8, 2012
How long is too long for a single method/function

A good goal is to make a function do exactly one thing. In realistic programming, this usually doesn't happen strictly, but it's still a good way to judge a function's length. If it's doing too much, you should definitely split it up. I try not to let my functions get past 20-30 lines unless absolutely necessary before I start looking for ways to break them up. A function that is 350 lines of code is almost definitely too large: even if there isn't much repeated code, you could benefit from splitting code into different functions just for simplicity in reading and understanding as well as for maintenance on your program.

More on reddit.com
🌐 r/learnprogramming
6
1
August 7, 2012
🌐
Wikibooks
en.wikibooks.org › wiki › Algorithms › Find_maximum › Python_method_1
Algorithms/Find maximum/Python method 1 - Wikibooks, open books for an open world
The code needs to be reviewed. def findmax(a): if len(a) == 0: return 0 curr_max = a[0] for i in a: if i > curr_max: curr_max = i return curr_max ... def imax( iterable, key=lambda x: x ): """returns largest item, as input could take iterator or sequence "key" function ...
🌐
W3Schools
w3schools.com › python › ref_func_max.asp
Python max() Function
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The max() function returns the item with the highest value, or the item with the highest value in an iterable.
🌐
Reddit
reddit.com › r/learnpython › question about max function in numpy source code, saving o(100) nanoseconds by assigning a function
r/learnpython on Reddit: Question about max function in numpy source code, saving O(100) nanoseconds by assigning a function
May 6, 2023 -

At this line: https://github.com/numpy/numpy/blob/v1.16.1/numpy/core/_methods.py#L16-L28

It says "saave those O(100) nanoseconds" and then assigns functions to variables, e.g. umr_maximum = um.maximum.reduce

I have a few questions,

  1. What does O(100) mean, is it "up to but no more than 100 nanoseconds"?

  2. Why does assigning to a variable save time? Doesn't it only cost time (and memory) to do the variable assignment?

I'm not trying to be pedantic I am genuinlely just wondering if there's anything I can learn from this small lighthearted comment! I am very new to both python as well as big O notation.

🌐
w3resource
w3resource.com › python › built-in-function › max.php
Python max() function - w3resource
August 19, 2022 - Example-2: Python max() function · x = [25, 100, 1500, 725] y = [10, 5] z = [35, 525, 98] # using max(iterable, *iterables, key) print('Maximum is:', max(x, y, z, key=len)) Output: Maximum is: [25, 100, 1500, 725] Python Code Editor: PREV : ...
Find elsewhere
🌐
Quora
quora.com › How-can-I-rewrite-Pythons-max-function
How to rewrite Python's max function - Quora
Answer (1 of 6): What you wrote doesn’t make sense. The key should be a function of one variable, that will be applied to each element of numbers_list. The whole expression [code]max(numbers_list, key=some_function) [/code]would evaluate to that element of numbers_list for which some_function r...
🌐
ThePythonGuru
thepythonguru.com › python-builtin-functions › max
Python max() function - ThePythonGuru.com
January 7, 2020 - # find largest item in the string print(max("abcDEF")) # find largest item in the list print(max([2, 1, 4, 3])) # find largest item in the tuple print(max(("one", "two", "three"))) 'two' # find largest item in the dict print(max({1: "one", 2: "two", 3: "three"})) 3 # empty iterable causes ValueError # print(max([])) # supressing the error with default value print(max([], default=0)) ... Trying to find largest value among the objects of different types causes an error. To customize the sort order we use the key named argument. It works exactly like the key named argument of the sorted() function.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-max-function
Python - max() function - GeeksforGeeks
July 15, 2025 - This code creates a list of strings, "string_list," containing ["Geeks", "for", "Geeks"]. It then uses the max() function to find and print the maximum string based on lexicographic order
🌐
Programiz
programiz.com › python-programming › methods › built-in › max
Python max()
The function returns the values of dictionaries. Based on the values (rather than the dictionary's keys), the key having the maximum value is returned.
🌐
KooR.fr
koor.fr › Python › API › python › builtins › max.wp
KooR.fr - Fonction max - module builtins - Description de quelques librairies Python
Cette fonction permet de calculer la valeur maximale parmi un ensemble de valeurs. Deux principales syntaxes d'appels sont supportées par cette fonction. Soit vous travaillez dans le contenu d'une collection qui peut être parcourue via une bouble for (list, tuple, set...). En Python, on parle souvent d' « itérable » pour qualifier une telle collection.
🌐
ZetCode
zetcode.com › python › max-builtin
Python max Function - Complete Guide
April 11, 2025 - The Person class implements __gt__ to compare by age. When we call max on a list of Person instances, Python uses this method. This pattern is useful when you want objects to have a natural ordering for comparison operations. The max function raises ValueError when used with empty iterables.
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › max.html
max — Python Reference (The Right Way) 0.1 documentation
Returns the largest item in an iterable or the largest of two or more arguments · max (collection[, key])
🌐
Unstop
unstop.com › home › blog › python max() function | all use cases with code examples
Python max() Function | All Use Cases With Code Examples
February 12, 2025 - The max() function in Python can be used to find the "largest" string from a set of strings based on different criteria. By default, max() compares the values themselves, but when we want to compare strings by a specific property—such as their length—we can use the key parameter. In the basic Python code example below, we have illustrated how to compare four strings by proving the key parameter and determining the maximum based on length.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-built-in-functions-all-any-max-and-min-in-python
How To Use the all, any, max, and min Functions in Python | DigitalOcean
October 14, 2020 - In this tutorial, you will learn how to use the Python built-in functions all, any, max, and min. Python includes a number of built-in functions—these are gl…
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › max() function in python: syntax, parameters, and examples
max() Function in Python: Syntax, Parameters & Examples
April 1, 2026 - When you compare separate values directly, max() checks each argument and returns the largest one. This form of the Python max function is useful when you already have individual values and do not need to place them in a container first.