Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Function That Outputs the Two Largest Values in a List of Numbers

Python Implement a Function That Outputs the Two Largest Values in a List of Numbers

Document Object Reference Manual Python3 Examples

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

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 analysis:

  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 initialize first_max and second_max to negative infinity, so that any number in the list will be greater than these two initial values.
  3. We iterate over each number in the list. If the current number is greater than first_max, we first_max assign the value of to second_max, then assign the current number to first_max. If the current number is not greater than first_max but is greater than second_max, we only update second_max。
  4. Finally, we return first_max and second_max。

Output result:

Example

(

99

,

99

)

Document Object Reference Manual Python3 Examples