KnowledgeBoat Logo
|
LoginJOIN NOW

Informatics Practices

Write a program to find the largest and the second largest elements in a given list of elements.

Python List Manipulation

10 Likes

Answer

nums = eval(input("Enter the list: "))

first = nums[0]
second = nums[0]

for num in nums[2:]:
    if num > first:
        second = first  
        first = num     
    elif num > second and num != first:
        second = num   

print("Largest element:", first)
print("Second largest element:", second)

Output

Enter the list: [2, 8, 10, 18, 15, 6]
Largest element: 18
Second largest element: 15

Answered By

3 Likes


Related Questions