Find the second highest number using looping in python.

Ocean community

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there,

Here is another option to what has already been mentioned:

list = [9, 6, 4, 10, 13, 2, 3, 5]
max = float('-inf')
second_last = float('-inf')
for x in list:
    if x > max:
        second_last = max
        max = x
    elif x > second_last and x != max:
        second_last = x


Hope that this helps!



Site Moderator
Site Moderator badge
September 14, 2022

Hi @kayakokulaanusha,

There is no need to loop, I assume you get these numbers from an array? Then you can sort them and get the second element. Something like this:

list_numbers = [24, 10, 60, 25, 9]  
# sorting the list  
print("The second largest element of the list is:", list_numbers[-2])  

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up