Instagram
youtube
Facebook
Twitter

Python Program to Find Top Two Maximum Numbers in a List

A Python Program to Find Top Two Maximum Numbers in a List

Code Explanation:

Function Definition:
top_two_maximum(lst) is defined to find the two largest unique numbers in the list.

Initial Values:
Both first_max and second_max are initialized to negative infinity (-inf).

Loop Through List:
Iterates through each number in the list.

Comparison & Update:

  • If number > first_max:
    first_max is updated and previous first_max becomes second_max.

     
  • If number > second_max and ≠ first_max:
    Then only second_max is updated.

     

Edge Case Handling:
If there's no second maximum (like in a list with all the same elements), a message is returned.

Return Result:
Returns a tuple containing the two highest unique numbers.

 

Program:

def top_two_maximum(lst):

    first_max = second_max = float('-inf')

    for num in lst:

        if num > first_max:

            second_max = first_max

            first_max = num

        elif num > second_max and num != first_max:

            second_max = num

    if second_max == float('-inf'):

        return "No second maximum found"

    return first_max, second_max

my_list = [10, 20, 45, 99, 65, 99, 70]

result = top_two_maximum(my_list)

print("Top two maximum numbers are:", result)