Write a Python program to find the second largest number in a list


This program is finding the second largest element in the given list 'num' of integers. It does this by first checking whether the length of the list is less than 2, in which case it prints the entire list, or if the length of the list is 2 and the first and second elements are the same, in which case it also prints the entire list. If neither of these conditions is met, the program then uses a for loop to iterate through the elements of the list and add any unique elements to a new list called 'uniq_items'. The program then sorts this list in ascending order using the sort() method, and then prints the second last element of this list, which is the second largest element in the original list.

Source Code

num = [ 82,4,56,78,4,34,5,100,9]
if (len(num)<2):
  print(num)
if ((len(num)==2)  and (num[0] == num[1]) ):
  print(num)
dup_items = set()
uniq_items = []
for x in num:
  if x not in dup_items:
    uniq_items.append(x)
    dup_items.add(x)
uniq_items.sort()    
print(uniq_items[-2])
 

Output

82

Example Programs