Report this

What is the reason for this report?

Find the second highest number using looping in python.

Posted on September 14, 2022

Ocean community



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!

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 @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  
list_numbers.sort()  
print("The second largest element of the list is:", list_numbers[-2])  

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

print(second_last)

Hope that this helps!

Best,

Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.