Find the second highest number using looping in python.

Ocean community

Submit an answer
Answer a question...

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])  

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.