The Wayback Machine - https://web.archive.org/web/20240922201828/https://www.geeksforgeeks.org/python-list-max-method/
Open In App

Python List max() Method

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python list max() function returns the maximum value present in the list.

Example:

Python
#creating a list
rand = [2,3,6,1,8,4,9,0]
#printing max element
print(max(rand))

Output
9

Definition of List max() Function

max() function in Python finds and returns the largest element in that list. Lets understand it better with an Example:

Python List max() Method Syntax:

max(listname)

Parameter

  • listname : Name of list in which we have to find the maximum value.

Returns : It return the maximum value present in the list.

How to Find Maximum Element in List in Python?

To find the maximum element in Python, you can use list max() function that returns max element from the list. Let’s understand it better with an example:

Python
#creating a list
number = [54,67,12,33,69,32]
#printing max element
print(max(number))

Output
69

Python List max() Method Example

Lets look at some examples to find max element in Python list:

Example 1:

In this example, we are going to find the maximum integer value in the list. For that, we have to make a list of some random integers and then use the Python list max() function to find the maximum value in the list. Let’s implement this using code.

Code:

Python
# Declaring a list with random integers.
list1 = [4, -4, 8, -9, 1]

# Store maximum value in a variable
# using Python list max() function.
maxValue = max(list1)

# Printing value stored in maxValue.
print(maxValue)

Output
8

Example 2:

In this example, we are going to find the maximum value from the list of characters. This is done by following same procedure as in example 1.

Python
# Declaring a list with random integers.
list1 = ['a', '$', 'e', 'E']

# Store maximum value in a variable
# using Python list max() function.
maxValue = max(list1)

# Printing value stored in maxValue.
print(maxValue)

Output
e

In this case of character values the max value is determined on the basis of their ASCII values. For example ASCII value of ‘e’ is 101 and ‘E’ is 69 therefore ‘e’ is larger.

Example 3:

In this example, we are going to try to find the maximum value from the list of mixed values such as integers and strings.

Code:

Python
# Declaring a list with mixed values.
list1 = ['a', '$', 'e', 3, 16]

# Store maximum value in a variable
# using Python list max() function.
maxValue = max(list1)

# Printing value stored in maxValue.
print(maxValue)

As we can see in the output this code gives the error because finding the maximum value between integers and string is not supported by Python list max() function.

Output:

Traceback (most recent call last):
File "/home/b98ffbce53474d196bfb2d69e59d0873.py", line 6, in <module>
maxValue = max(lis)
TypeError: '>' not supported between instances of 'int' and 'str'

Below is the solution of above example no 3-

Solution :

We can find the maximum value between integers and string to convert integer into char but according to ASCII table only.

Python
# Declaring a list with mixed values.
list1 = ['!', '$', '/', '3', '61']

# Store maximum value in a variable
# using Python list max() function.
maxValue = max(list1)

# Printing value stored in maxValue.
print(maxValue)

Output
61

Note- integers lie between 48 to 57 from 1 to 9 in ascii table and it will consider only first char
of a string. Let if in above example there will be 16 instead of 61 then output will be 3 because 
it will consider first char which is 1 in 16.

Complexity- 

The time complexity of max() function in python is O(n) .

We have covered the definition, syntax and examples of max() function in Python. List max() method is very important for arithmetic projects and can save you a lot of time.

Hope you understood the use and functioning of max() function!

Python List max() Method – FAQs

What Does max() Do in Python?

The max() function in Python returns the largest item in an iterable (like a list or tuple) or the largest of two or more arguments. If the provided iterable is empty, it raises a ValueError. You can also pass a key function to max() to specify a method of determining the order.

Example:

numbers = [10, 20, 30, 40, 50]
result = max(numbers)
print(result) # Output: 50

How to Get Max Value from List in Python Without max Function?

To find the maximum value in a list without using the max() function, you can use a simple loop to iterate through the list and keep track of the largest number.

Example:

numbers = [10, 20, 30, 40, 50]
largest = numbers[0] # Start by assuming the first number is the largest

for number in numbers:
if number > largest:
largest = number

print(largest) # Output: 50

How to Get the Max of a List of Lists in Python?

To find the maximum value in a list of lists, you can use a nested approach with the max() function. You first find the maximum of each sublist and then find the maximum of those maxima.

Example:

lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
max_value = max(max(sublist) for sublist in lists)
print(max_value) # Output: 9

What is Max in NumPy?

In NumPy, max() is a function used to compute the maximum value of an array or along a specified axis. The function is highly optimized for performance and can handle very large arrays efficiently compared to native Python loops.

Example:

import numpy as np

array = np.array([1, 2, 3, 4, 5])
max_value = np.max(array)
print(max_value) # Output: 5

What are the MIN() and MAX() Functions in Python? What Do They Do?

In Python:

  • MIN(): The min() function returns the smallest item in an iterable or the smallest of two or more arguments. Like max(), it can also take a key function to determine how to compare the elements.
  • MAX(): The max() function, as discussed, returns the largest item in an iterable or the largest of two or more arguments.

Both functions are useful for finding the extremities in sequences of values and can be customized with a key parameter to specify how elements are compared.

Example using both min() and max():

numbers = [10, 20, 30, 40, 50]
print(min(numbers)) # Output: 10
print(max(numbers)) # Output: 50

These functions are essential tools in data analysis, optimization problems, and any scenario where you need to quickly assess the range or bounds of a set of values in Python



Previous Article
Next Article

Similar Reads

List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Python | Min/Max value in float string list
Sometimes, while working with a Python list, we can have a problem in which we need to find min/max value in the list. But sometimes, we don't have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Let's discuss a way in which this problem
6 min read
Python | Decimal max() method
Decimal#max() : max() is a Decimal class method which compares the two Decimal values and return the max of two. Syntax: Decimal.max() Parameter: Decimal values Return: the max of two. Code #1 : Example for max() method # Python Program explaining # max() method # loading decimal library from decimal import * # Initializing a decimal value a = Deci
2 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace &amp; expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Python String | max()
max() is an inbuilt function in Python programming language that returns the highest alphabetical character in a string. Syntax: max(string) Parameter: max() method takes a string as a parameter Return value: Returns a character which is alphabetically the highest character in the string. Below is the Python implementation of the method max() Pytho
1 min read
Python | Pandas Series.max()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.max() function return the maximum of the underlying data in the given Series ob
3 min read
Python | Pandas dataframe.max()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.max() function returns the maximum of the values in the given object. If the input is a series, the method will return
2 min read
Python | Pandas Index.max()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.max() function returns the maximum value of the Index. The function works with both numerical as well as the string type ob
2 min read
Python | Pandas TimedeltaIndex.max
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.max() function return the maximum value of the TimedeltaIndex object or maximum along an axis. Syntax : TimedeltaI
2 min read
Use of min() and max() in Python
Prerequisite: min() max() in Python Let's see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as argum
2 min read
Python | Numpy matrix.max()
With the help of Numpy matrix.max() method, we can get the maximum value from given matrix. Syntax : matrix.max() Return : Return maximum value from given matrix Example #1 : In this example we can see that we are able to get the maximum value from a given matrix with the help of method matrix.max(). # import the important module in python import n
1 min read
SymPy | Permutation.max() in Python
Permutation.max() : max() is a sympy Python library function that returns the maximum value in the permutation. Syntax : sympy.combinatorics.permutations.Permutation.max() Return : maximum value in the permutation. Code #1 : max() Example # Python code explaining # SymPy.Permutation.max() # importing SymPy libraries from sympy.combinatorics.partiti
1 min read
Python | Max/Min value in Nth Column in Matrix
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the minimum and maximum value of a particular column. This can have a possible application in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Method 1: Using max()/min() + zip() This task ca
7 min read
Numpy recarray.max() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record arrays allow the fields to be accessed as members of th
4 min read
Max Heap in Python
A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored a index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2. Examples of Max Heap : How is Ma
7 min read
Python SQLAlchemy - Group_by and return max date
In this article, we are going to see how to use Group_by and return max date SQLAlchemy in Python. Installing SQLAlchemy SQLAlchemy is available via pip install package. pip install sqlalchemy However, if you are using flask you can make use of its own implementation of SQLAlchemy. It can be installed using - pip install flask-sqlalchemyExample Bef
2 min read
Python - max() function
Python max() function returns the largest item in an iterable or the largest of two or more arguments. It has two forms. max() function with objectsmax() function with iterablePython max() function With ObjectsUnlike the max() function of C/C++, the max() function in Python can take any type of object and return the largest among them. In the case
4 min read
max() and min() in Python
This article brings you a very interesting and lesser-known function of Python, namely max() and min(). Now when compared to their C++ counterpart, which only allows two arguments, that too strictly being float, int or char, these functions are not only limited to 2 elements, but can hold many elements as arguments and also support strings in their
3 min read
How To Fix “Connectionerror : Max retries exceeded with URL” In Python?
When the Python script fails to establish a connection with a web resource after a certain number of attempts, the error 'Connection error: Max retries exceeded with URL' occurs. It's often caused by issues like network problems, server unavailability, DNS errors, or request timeouts. In this article, we will see some concepts related to this error
3 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Max and Min date in Pandas GroupBy
Prerequisites: Pandas Pandas GroupBy is very powerful function. This function is capable of splitting a dataset into various groups for analysis. Syntax: dataframe.groupby([column names]) Along with groupby function we can use agg() function of pandas library. Agg() function aggregates the data that is being used for finding minimum value, maximum
1 min read
Mahotas - Getting Labeled Max Array
In this article we will see how we can obtain the labeled max array of the in mahotas. Labeled images are integer images where the values correspond to different regions. I.e., region 1 is all of the pixels which have value 1, region two is the pixels with value 2, and so on. By convention, region 0 is the background and often handled differently.
3 min read
Pandas - GroupBy One Column and Get Mean, Min, and Max values
We can use Groupby function to split dataframe into groups and apply different operations on it. One of them is Aggregation. Aggregation i.e. computing statistical parameters for each group created example - mean, min, max, or sums. Let's have a look at how we can group a dataframe by one column and get their mean, min, and max values. Example 1: i
2 min read
PyQtGraph – Getting Quick Min Max of Image View
In this article, we will see how we can get the min-max value of data of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video,
4 min read
How to select min and max from table by column score in SQLAchemy?
In this article, we are going to fetch min and max values from column scores in the SQL table using the SQLAlchemy module. SQLAlchemy is an awesome and easy-to-use python module to connect with SQL and use the features and powers of SQL in python. Here, we are provided with a table that has a column named "score" and our task is to find out the max
3 min read
How to Do SELECT MAX in Django?
When working with databases in Django, we often need to find the highest value of a specific field in a model. Let's say, find the book with the highest price, the product with the highest discount, etc. This is like doing a SELECT MAX query in SQL. In this article, we'll learn how to find the max value using the `aggregate()` and `order_by()`, met
4 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Practice Tags :