Python Find Maximum and Minimum Elements in a List

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]: Define a list containing multiple integers.
  2. max_value = max(numbers): Use themax()function to find the maximum value in the list and assign it to the variablemax_value。
  3. min_value = min(numbers): Use themin()function to find the minimum value in the list and assign it to the variablemin_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 对象参考手册Python3 Examples

Other extensions