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


This program is checking for unique second smallest element in the list "num" which is a list of integers. It first checks if the length of the list is less than 2. If it is, the program just prints the list as it is. If the length of the list is 2 and both elements are the same, it also prints the list as it is.

Otherwise, it creates two new empty lists: "dup_items" and "uniq_items". It then iterates through every element "x" in the original "num" list. If "x" is not already in "dup_items", it adds it to "uniq_items" and also adds it to "dup_items" using the add() method. After the iteration is done, it sorts the uniq_items list, and finally prints the second element in the list ( index 1, as list indexing starts from 0)

Source Code

num = [ 2,4,56,78,4,34,5,8,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[1]   )

Output

4

Example Programs