Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Find the Maximum and Minimum Elements in a List

Python Find the Maximum and Minimum Elements in a List

Document Object Reference Manual Python3 Examples

In Python, we can use the built-in max() and min() functions to quickly find the maximum and minimum values in a list. These two functions return the maximum and minimum elements in the list, respectively.

Example

Define a list

numbers

=

[

3

,

1

,

4

,

1

,

5

,

9

,

2

,

6

,

5

,

3

,

5

]

Use the max() function to find the maximum value

max_value

=

max

(

numbers

)

Use the min() function to find the minimum value

min_value

=

min

(

numbers

)

Output result

print

(

"The maximum value in the list is:"

,

max_value

)

print

(

"The minimum value in the list is:"

,

min_value

)

Code analysis:

  1. numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]: Define a list containing multiple integers.
  2. max_value = max(numbers): When using max() function to find the maximum value in the list and assign it to the variable max_value。
  3. min_value = min(numbers): When using min() function to find the minimum value in the list and assign it to the variable min_value。
  4. print("列表中的最大值是:", max_value): Output the maximum value in the list.
  5. print("列表中的最小值是:", min_value): Output the minimum value in the list.

Output result:

列表中的最大值是: 9
列表中的最小值是: 1

Document Object Reference Manual Python3 Examples