Python Program to Find Smallest Number in an Array

Write a Python Program to Find Smallest Number in an Array. The numpy min function returns the Smallest or minimum value in an array. We use this numpy min function to return the Smallest item in a number and string array.

# Smallest Array Item
import numpy as np
smtarr = np.array([14, 27, 99, 10, 50, 65, 18, 4, 195, 100])
print("Numeric Numpy Array Items = ", smtarr)
print("The Smallest Number in this Numpy Array = ", min(smtarr))

strsmtarr = np.array(['UK','USA','India', 'Japan'])
print("String Numpy Array Items = ", strsmtarr)
print("The Smallest Number in this Numpy Array = ", min(strsmtarr))
Python Program to Find Smallest Number in an Array 1

Python Program to Find Smallest Number in an Array.

We used the numpy sort function to sort the array in ascending order and print the first index position number, the Smallest.

# Smallest Array Ite
import numpy as np
smtarr = np.array([99, 14, 150, 11, 184, 5, 190])
print("Numeric Numpy Array Items = ", smtarr)

print(type(smtarr))
smtarr.sort()
print("The Smallest Number in this Numpy Array = ", smtarr[0])

Smallest Python Numpy Array Item output

Numeric Numpy Array Items =  [ 99  14 150  11 184   5 190]
<class 'numpy.ndarray'>
The Smallest Number in this Numpy Array =  5

In this Python example, we assigned the first value as Smallest, and the for loop range begins at one and traverses up to smtarr length minus one. The if condition (if(smallest > smtarr[I])) examines whether the current numpy array element is greater than the Smallest. If True, assign that value (smallest = smtarr[I]) to the Smallest variable and the (position = i) index value to the position variable.

# Smallest Array Item
import numpy as np
smtarr = np.array([14, 27, 99, 10, 50, 65, 18, 4, 195, 100])
print("Numeric Numpy Array Items = ", smtarr)

smallest = smtarr[0]
for i in range(1, len(smtarr)-1) :
    if(smallest > smtarr[i]) :
        smallest = smtarr[i]
        position = i
        
print("The Smallest Number in this Numpy Array   = ", smallest)
print("The Index Position of the Smallest Number = ", position)

Python Numpy Array Smallest Item output

Numeric Numpy Array Items =  [ 14  27  99  10  50  65  18   4 195 100]
The Smallest Number in this Numpy Array   =  4
The Index Position of the Smallest Number =  7