Finding the maximum value in a list in Python

by Alex
Finding the maximum value in a list in Python

In this article, we will learn how to find the maximum value in a list in Python. For a comprehensive understanding, we will look at the use of some built-in functions, simple approaches, and small implementations of well-known algorithms. First, let’s take a brief look at what a list is in Python and how to find the maximum value or just the largest number in it.

List in Python

Python has a built-in data type called a list. In its essence, it strongly resembles an array. But unlike the latter, the data inside a list can be of any type (not necessarily one): it can contain integers, strings, or floating point values, or even other lists. The data stored in a list is defined as comma-separated values enclosed in square brackets. Lists can be defined by using any variable name and then assigning different values in square brackets to it. It is ordered, modifiable, and allows for duplicate values. For example:

list1 = ["Viktor", "Artem", "Roman"]
list2 = [16, 78, 32, 67]
list3 = ["apple", "mango", 16, "cherry", 3.4]

In the following, we will look at possible Python code that implements a search for the largest item in a list consisting of the items being compared. Our examples will use the following methods/functions:

  1. Built-in max()function
  2. Brute force method (brute force)
  3. Reduce()function
  4. Heap Queue algorithm (queue with priority)
  5. Function sort()
  6. Function sorted()
  7. Tail recursion method

#1 Finding the maximum value using the max() function

This is the simplest and most straightforward approach to finding the largest item. The Python function max() returns the largest element of an iterable object. It can also be used to find the maximum value between two or more parameters. In the example below, the list is passed to the max function as an argument.

list1 = [3, 2, 8, 5, 10, 6]
max_number = max(list1)
print("Maximum number:", max_number)
Biggest number: 10

If the list elements are strings, they are first ordered alphabetically and then the largest string is returned.

list1 = ["Viktor", "Artem", "Roman"]
max_string = max(list1, key=len)
print("The longest string:", max_string)
The longest string: Viktor

#2 Search for the maximum value by brute force

This is the simplest implementation, but it is a bit slower than the max() function because we use this algorithm in a loop. In the example above, we defined the large() function to find the maximum value. It takes a list as a single argument. To store the value found, we use the variable max_, which is initially assigned to the first item in the list. In the for loop, each item is compared to this variable. If it is greater than max_, we store the value of that element in our variable. After comparing with all members of the list, the max_ is guaranteed to contain the largest element.

def large(arr) 
    max_ = arr[0]
   for ele in arr:
       if ele > max_:
           max_ = ele
   return max_ 

list1 = [1,4,5,2,6]
result = large(list1)
print(result) # will return 6

#3 Finding the maximum value with reduce()

In functional languages, reduce() is an important and very useful function. In Python 3, the reduce() function has been moved to a separate module in the standard library called functools. This decision was made to encourage developers to use loops as they are more readable. Consider the example below of using reduce() in two different ways. In this variant, reduce() takes two parameters. The first is the max keyword, which means to find the maximum number, and the second argument is an iterable object.

from functools import reduce

list1 = [-1, 3, 7, 99, 0]
print(reduce(max, list1)) # output: 99

Another solution shows an interesting construction using a lambda function. The reduce() function takes a lambda function as an argument, and that in turn receives a condition and a list to check the maximum value.

from functools import reduce

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

#4 Finding the Maximum Value with the Priority Queue

Heapq is a very useful module for implementing a minimum queue. More precisely, it provides an implementation of a priority queuing algorithm based on a heap, known as heapq. An important property of such a heap is that its smallest element will always be the root element. In the example above, we use heapq.nlargest() to find the maximum value.

import heapq

list1 = [-1, 3, 7, 99, 0]
print(heapq.nlargest(1, list1)) # -> [99]

The above example imports the heapq module and takes a list as input. The function takes n=1 as the first argument, since we need to find one maximum value, and the second argument is our list.

#5 Finding the maximum value with sort()

This method uses the sort() function to find the largest element. It takes a list of values as input, then sorts it in ascending order and outputs the last item in the list. The last item in the list is list[-1].

list1 = [10, 20, 4, 45, 99]
print("Highest number:", list1[-1])
Maximal number: 99

#6 Finding the maximum value with sorted()

This method uses the sorted() function to find the largest element. It takes a list of values as input. The sorted() function then sorts the list in ascending order and outputs the largest number.

sorted_list = sorted(list1)
result = sorted_list[-1]
print(result) # -> 41

#7 Finding the Maximum Value with Tail Recursion

This method is not very convenient, and sometimes programmers consider it useless. This solution uses recursion and is therefore quite difficult to understand quickly. In addition, such a program is very slow and requires a lot of memory. This is because, unlike pure functional languages, Python is not optimized for tail recursion, which leads to many stack frames: one for each function call.

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

result = find_max(list1)
print(result) # -> 4


In this article, we learned how to find the maximum value from a given list using several built-in functions such as max(), sort(), reduce(), sorted(), and other algorithms. We wrote our own code to try the brute-force, tail recursion, and priority queue algorithms.

Related Posts