search

How to find the maximum value in a list in Python?

To find the maximum value in a list in Python, you can use the built-in max() function. Here's an example:

my_list = [4, 2, 9, 1, 7]
maximum = max(my_list)
print(maximum)
# Output: 9

In this example, the max() function is used to find the maximum value in the list my_list. The resulting maximum value is then stored in the variable maximum and printed.

The max() function takes an iterable, such as a list, as an argument and returns the maximum value in that iterable.

Note that the max() function returns the maximum value based on the default comparison, which is the natural ordering of the elements. If the list contains elements of different types, they should be compatible for comparison (e.g., numbers or strings). If you have a list of complex objects and want to find the maximum based on a specific attribute or custom comparison, you can use the key parameter of the max() function or use a lambda function in conjunction with max() to define a custom comparison criterion.

Related Questions You Might Be Interested