user5458829
user5458829

Reputation: 163

How to find 2nd largest number in a list in python

How to find 2nd highest number in list.element in list can repeat. when all elements in list are same it should give element not present

Upvotes: 0

Views: 75

Answers (1)

dmitryro
dmitryro

Reputation: 3506

Create a function taking a list as argument:

def find_second(l):
    # Take a set to remove duplicates and check the length
    if len(set(l)) <= 1:
        return "Not present"
    else:
        return sorted(l)[1]

Run some tests:

l1 = [1] 
r1 = find_second(l1)
# Prints Not present
print(r)

l2 = [1, 3, 2]
r2 = find_second(l2)
# Prints 2
print(r)

Upvotes: 1

Related Questions