HOW TO FIND THE SECOND LARGEST ELEMENT IN A LIST IN PYTHON
l = [ 11,15,19 ]
#Use dummy variables
mx = 0
smx = 0
#Iterate over the list with x variable
for x in l:
#If value of x is greater than x, then swap the values of smx to mx and mx to x otherwise get the second largest value by funneling the range
if x > mx:
smx = mx
mx = x
elif x < mx and x > smx:
smx = x
print(mx,smx)
Alternatively a function can be defined
def sln(l):
mx = 0
smx = 0
for x in l:
if len(l) <= 1:
return -1
else:
if x > mx:
smx = mx
mx = x
elif x < mx and x > smx:
smx = x
elif smx == 0:
smx = -1
return smx