Python Program to Find the Second Smallest Number in a List

This article is created to cover some programs in Python that find and print the second-smallest element or number in a list entered by the user. Here is a list of programs:

Find the second-smallest number in a list of 10 elements

The question is: write a Python program to find the second-smallest number in a list using the for loop. Here is its answer:

nums = []
print("Enter 10 Numbers (Elements) for List: ")
for i in range(10):
  nums.append(int(input()))

small = nums[0]
for i in range(10):
  if small>nums[i]:
    small = nums[i]

secondSmall = nums[0]
for i in range(10):
  if secondSmall>nums[i]:
    if nums[i]!=small:
      secondSmall=nums[i]

print("\nSecond Smallest Number is: ")
print(secondSmall)

Here is its sample run:

python find second smallest number in list

Now supply any 10 elements or numbers for the list, say 4, 5, 6, 2, 1, 0, 3, 7, 8, 9, and press the ENTER key to find and print the second smallest number from the list:

find second smallest number in list python

Find the second-smallest number in a list of n elements

This program allows the user to define the size of a list along with its elements (numbers) to find and print the second-smallest number from the given list. Let's have a look at the program given below:

nums = []
print(end="Enter the Size of List: ")
listSize = int(input())
print(end="Enter " +str(listSize)+ " Numbers for List: ")
for i in range(listSize):
  nums.append(int(input()))

small = nums[0]
for i in range(listSize):
  if small>nums[i]:
    small = nums[i]

secondSmall = nums[1]
for i in range(listSize):
  if secondSmall>nums[i] and nums[i]!=small:
    secondSmall = nums[i]

if small == secondSmall:
  print("\nSecond Smallest Number doesn't exist!")
else:
  print("\nSecond Smallest Number = " + str(secondSmall))

Here is its sample run with user input: 5 as size and 1, 2, 3, 4, and 5 as five elements or numbers:

find second smallest element in list python

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!