Python Find the Maximum and Minimum Elements in a List
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
(
"The maximum value in the list is:"
,
max_value
)
(
"The minimum value in the list is:"
,
min_value
)
Code analysis:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]: Define a list containing multiple integers.max_value = max(numbers): When usingmax()function to find the maximum value in the list and assign it to the variablemax_value。min_value = min(numbers): When usingmin()function to find the minimum value in the list and assign it to the variablemin_value。print("列表中的最大值是:", max_value): Output the maximum value in the list.print("列表中的最小值是:", min_value): Output the minimum value in the list.
Output result:
列表中的最大值是: 9
列表中的最小值是: 1
Python3 Examples