Python implementation of a function that outputs the two largest values from a numeric list

Document 对象参考手册Python3 Examples

We will write a Python function that takes a list of numbers as input and returns the two largest values in the list. We will use simple logic to implement this function.

Example

def find_two_max(numbers):
    if len(numbers)  first_max:
            second_max = first_max
            first_max = number
        elif number > second_max:
            second_max = number

    return first_max, second_max

# Example usage
numbers = [10, 20, 4, 45, 99, 99]
print(find_two_max(numbers))

Code explanation:

  1. First, we check whether the length of the list is less than 2. If so, we return an error message because we need at least two numbers to find the two largest values.
  2. We initializefirst_maxandsecond_maxto negative infinity, so that any number in the list will be greater than these two initial values.
  3. We iterate through each number in the list. If the current number is greater thanfirst_max, we assignfirst_maxthe value ofsecond_max, then assign the current number tofirst_max. If the current number is not greater thanfirst_maxbut greater thansecond_max, we only updatesecond_max。
  4. Finally, we returnfirst_maxandsecond_max。

Output result:

Example

(99, 99)

Document 对象参考手册Python3 Examples

Other extensions