Python: Calculating the Largest and 2nd largest value in the list

I am trying to calculate the largest and 2nd largest values in Python. Following is my code:

def find_largest_and_second_Largest(list1):
    maxV = max(list1[0], list1[1])
    max2V = min(list1[0], list1[1])
    for i in range (2, len(list1)):
        if (maxV > list1[i]):
            if (max2V > list1[i]):
                max2V = list1[i]
            maxV= list1[i]
            max2V = maxV
    print("Largest ="+ str(max))
    print("2nd Largest =" + str(max2V))

The output is:
Largest =
2nd Largest =34

Somebody please guide me.

I think your error is here

    print("Largest ="+ str(max))

you have str(max) instead of str(maxV)

BUT, I think this would seem more pythonic and easier to read:

def find_largest_and_second_largest(list1):
  maxV = max(list1)
  max2V = min(list1)
  if  len(list1) > 2:
    for i in list1:
      max2V = i if (i<maxV and i>max2V) else max2V
  print("Largest ="+ str(maxV))
  print("2nd Largest =" + str(max2V))

in fact if you were ‘code golfing’ you could even remove my if len(list1) > 2: and it would still work.

Hope that helps.:slight_smile:


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.