Six ways to find max value of a list in Python
![]()
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:
The C-like one:
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:
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.
Above is equivalent to sorted(A, reverse=True)[:1] (because n = 1) which is yet another solution.
The functional, fancy, but useless one:
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?
Find the greatest (largest, maximum) number in a list of numbers
How can I easily find the greatest number in a given list of numbers?
See also How do I find the maximum (larger, greater) of 2 numbers? — in that special case, the two values can also be compared directly.
7 Answers 7
![]()
![]()
You can use the inbuilt function max() with multiple arguments:
or in fact anything iterable.
This approach is without using max() function
Also if you want to find the index of the resulting max,
Direct approach by using function max()
max() function returns the item with the highest value, or the item with the highest value in an iterable
Example: when you have to find max on integers/numbers
Example: when you have string
It basically returns the name with the highest value, ordered alphabetically.
Поиск наибольшего и наименьшего числа в списке в Python
Вы можете найти наибольший номер списка в Python, используя функцию sort() или более простой цикл for.
Использование функции sort() довольно лаконично, но использование цикла For является наиболее эффективным. Мы рассмотрим эти два подхода на примерах.
Пример 1
Мы знаем, что встроенная функция sort() сортирует список в порядке возрастания или убывания. После сортировки списка у вас будет самый большой номер в конце списка, если вы отсортировали его в порядке возрастания, или в начале списка, если вы отсортировали его в порядке убывания.
В следующем примере мы отсортируем данный список в порядке возрастания. Конечно, последний номер отсортированного списка – это самый большой номер.
a [-1] выбирает последний элемент в списке.
Пример 2: с помощью цикла For
Хотя найти наибольшее число с помощью функции sort() легко, использование цикла For делает это относительно быстрее с меньшим количеством операций.
В этом примере мы приняли список и инициализировали переменную ln с наибольшим числом первым элементом списка. Если в списке нет элементов, ln инициализируется значением None.
Повторяйте цикл для каждого элемента в списке. Во время каждой итерации мы проверяем, меньше ли наибольшее число этого элемента. В этом случае мы обновляем самое большое число с помощью элемента.
Когда вы завершите обход списка, вы получите наибольший номер списка в вашей переменной.
Вы можете найти наименьший номер списка в Python, используя функцию min(), функцию sort() или цикл for.
- встроенную функцию min();
- функцию сортировки sort();
- Цикл For.
Выберите один, исходя из требований вашей программы или ваших личных рекомендаций по производительности.
Пример 1: с помощью min()
Функция min() может принимать список в качестве аргумента и возвращать минимум элементов в списке.
В этом примере мы возьмем список чисел и найдем наименьшее из них с помощью функции min().
Пример 2: с помощью функции sort()
Мы знаем, что функция sort() сортирует список в порядке возрастания или убывания. После сортировки списка у вас будет наименьшее число в начале списка, если вы отсортировали его в порядке возрастания, в конце списка или в порядке убывания.
Пример 3: с помощью цикла for
Хотя найти наименьшее число с помощью функции sort() легко, использование For цикла делает это относительно быстрее с меньшим количеством операций. Кроме того, мы не меняем порядок элементов в данном списке.
Python How to Find the Largest Number in a List
To find the largest number in a list in Python:
- Set the first element as the largest number candidate.
- Loop through the list of numbers.
- Update the largest number candidate if a number is greater than it.
Here is how it looks in code:
This is the naive implementation of finding the largest number.
But there are also some useful built-in mechanisms you can use.
In this guide, you learn different ways to find the maximum value in a list in Python.
The max() Function — Find the Largest Element of a List
In Python, there is a built-in function max() you can use to find the largest number in a list.
To use it, call the max() on a list of numbers. It then returns the greatest number in that list.
Here is an example:
Alternative Approaches to Finding the Largest Number in a List
Now you know two straightforward ways to find the largest number in a list in Python.
Let’s take a look at some more uncommon approaches.
Reduce() Function
You can also use the functools reduce() function to find the largest number in a list.
Before we do that, it is important to understand how the reduce() function works.
The reduce function takes two parameters:
- A function that is applied for each element of an iterable.
- An iterable, such as a list.
- Takes the first two elements of a sequence and calls the function on them.
- Takes the previous result, and calls the function on the result and the next number in the list.
- This process continues until there are no elements left in the list.
To learn more about the reduce() function, check this article.
Anyway, let’s use the reduce() function to find the largest element in a list.
Reduce() with the built-in max() Function
Here is an example of how you can use reduce to find the largest number in a list:
The reduce() function applies the max() function for each element as described in the previous chapter.
- It starts with the two first elements and finds the largest of the two
- Then takes the result and compares it with the third element.
- This process continues until there are no numbers left in the list.
Let’s also see another, perhaps a bit more demonstrative example.
Reduce() with a Custom Max Function
Another way you can use reduce() to find the largest number in a list is by implementing the max() function yourself.
Reduce() with a Lambda Function
And the 3rd approach is to use reduce() with a lambda expression.
This means you define the max function inline in the reduce() function call.
The lambda x, y: y if x < y else x part does the same as the my_max() function in the previous example.
Notice that the if-else statement is shortened to a one-liner expression.
Find The Largest Number Using a Heap Queue
The built-in heapq module in Python comes in with an implementation of the priority queue algorithm.
In short, a heap is a binary tree where each parent node has a value less than or equal to the value of its children.

You can use the heapq.nlargest() function to figure out the largest number(s) in a list.
Conclusion
Today you learned how to find the largest number in a list.
First, you used the “brute-force” method to loop through the list while keeping track of the largest element.
Then you saw how the built-in max() function does the job for you.
Finally, you saw uncommon alternatives, such as using reduce() with lambdas or a heap queue.
Each of these approaches gets the job done for you.
Feel free to pick the approach that is best for your situation.
If I had to find the largest element, I would pick the most readable approach, that is, the built-in max() function.