Python implementation of a function that outputs the two largest values from a numeric list
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))
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:
- 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.
- We initialize
first_maxandsecond_maxto negative infinity, so that any number in the list will be greater than these two initial values. - We iterate through each number in the list. If the current number is greater than
first_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。 - Finally, we return
first_maxandsecond_max。
Output result:
Example
(99, 99)
Python3 Examples