Write a Python program to find second smallest number in an array

In this example, we will see, Python code to find the second smallest number from the array, the largest number from an array, and the Smallest number from an array.

How to find the largest and smallest number in an array.

In this program, we will consider the first element as the largest and compare it with the remaining elements in the array. If any element is greater than the number present in the largest we will assign that element to largest. Similarly, we will perform the same function for the smallest.

How to find the second smallest number in an array.

For finding the second smallest element we need to iterate the whole array and should check the element should not be the smallest element.

What is the largest, smallest and second smallest element?

Input: Array elements = [5, 10, 15, 20, 25]

Output: The largest element is 25

The smallest element is 5

The second smallest element is 10

Algorithm to print the largest, smallest, and second smallest number in an array:

  • Initialize an array.
  • Initialize the largest and smallest element to the 0th element of the array. Iterate the array using a for loop and check whether the element is greater or smaller than the assigned values. If greater assign that element to the largest and if smaller assign that element to the smallest. Similarly, the second smallest element is also found.
  • Print the largest, smallest, and second smallest element.

Python program to find the second smallest number in an array.

Method 1:

from array import *
arr = array('i', [])
n = int(input("enter number of elements"))
for i in range(n):
    arr.append(int(input("enter the array elements")))

print("entered array is:")
for i in range(len(arr)):
    print(arr[i])


def secsmall(arr):
    largest = arr[0]
    smallest = arr[0]
    secsmallest = None
    for item in arr[1:]:
        if(item > largest):
            largest = item
        if(item < smallest):
            secsmallest = smallest
            smallest = item
        elif(secsmallest == None or secsmallest > item):
            secsmallest = item

    print("Largest element is:", largest)
    print("Smallest element is:", smallest)
    print("Second Smallest element is:", secsmallest)

secsmall(arr)

Output: Printing the largest, smallest and second smallest

Method 2:

from array import *
arr = array('i', [])
n = int(input("enter number of elements"))
for i in range(n):
    arr.append(int(input("enter the array elements")))

print("entered array is:")
for i in range(len(arr)):
    print(arr[i])

largest = max(arr)
print("Largest element is",largest)
smallest = min(arr)
print("Smallest number is", smallest)
arr.remove(smallest)
secsmall = min(arr)
print("Second Smallest number is",secsmall)

Output: Printing the largest, smallest and second smallest