Python Program to Find Smallest Number in an Array

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

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.

import numpy as np
smtarr = np.array([99, 14, 150, 11, 184, 5, 190])
print(smtarr)

print(type(smtarr))
smtarr.sort()
print(smtarr[0])

Output

[ 99  14 150  11 184   5 190]
<class 'numpy.ndarray'>
5

In this 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 or not. If True, assign that value to the Smallest variable and the (position = i) index value to the position variable.

import numpy as np
smtarr = np.array([14, 27, 99, 10, 50, 65, 18, 4, 195, 100])
print(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   = ", smallest)
print("The Index Position = ", position)

Output

[ 14  27  99  10  50  65  18   4 195 100]
The Smallest Number   =  4
The Index Position =  7