Six ways to find max value of a list in Python

Sometime ago I read similar article on JavaScript, I thought that it would be a nice little challenge to came up with couple of Python solutions on this topic.

The obvious one:


Using builtin max() function is most pythonic and the best solution in 99.5% of cases (I checked! ;)). People new to Python might not know that max() takes iterable or list of arguments, and also a key= keyword argument so we can get something like this:

>>> a = (0,3)>>> b = (1,2)>>> c = (2,1)>>> max(a, b, c, key=lambda x: x[1])(0,3)

The C-like one:

def max(arr): max_ = arr[0] for item in arr: if item > max_: max_ = item return max_

Not to much to write about? This is the simplest implementation, since it?s written in Python it will be much slower than using the builtin max() which is implemented in C.

The functional one:

In functional languages reduce() is used a lot, in Python3 it was actually moved to a separate module in the standard library – functools. This decision was made to encourage developers to use loops, as they are more readable. There are couple of ways to use reduce in this case:

>>> A = [-1, 3, 7, 99, 0]>>> reduce(A, max)99>>> reduce(A, lambda x, y: x if x > y else y)99

The second solution is highly unreadable, but it shows an interesting construct using lambda function.

The sometimes useful one:

Heapq is a very useful module for implementing a min queue. For our purposes we can use function heapq.nlargest() which returns a list of n largest values.

>>> A = [-1, 3, 7, 99, 0]>>> import heapq>>> heapq.nlargest(1, A)[99]

Above is equivalent to sorted(A, reverse=True)[:1](because n = 1) which is yet another solution.

The functional, fancy, but useless one:

def max(arr, max_=None): if max_ is None: max_ = arr.pop() current = arr.pop() if current > max_: max_ = current if arr: return max(arr, max_) return max_

This solution uses iterative recursion, besides being highly over complicated (well, most of this solutions are) it?s also very slow and memory-consuming. This is because unlike pure functional languages Python doesn?t optimize for tail recursion, so every call to max() is being held on the stack. I wrote a bit more on this topic here: Tail recursion theory made simple.

Can you think of more fancy ways to get a max value from a list?


No Responses

Write a response