Python Find Maximum and Minimum Elements in a List
In Python, we can use the built-inmax()andmin()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 the result
print("The maximum value in the list is:", max_value)
print("The minimum value in the list is:", min_value)
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 the result
print("The maximum value in the list is:", max_value)
print("The minimum value in the list is:", min_value)
Code explanation:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]: Define a list containing multiple integers.max_value = max(numbers): Use themax()function to find the maximum value in the list and assign it to the variablemax_value。min_value = min(numbers): Use themin()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 列表中的最小值是: 1Other extensions
Python3 Examples