Write a Python Program to Find the Smallest Number in an Array. The numpy module has a built-in min() function to return the least value. Otherwise, you can. use the for loop or while loop to iterate the array items and if statement to find the least item.
Python Program to Find the Smallest Number in an Array using min function
The numpy min function returns the Smallest or minimum value in an array. This numpy function returns the minimum item in a number and string array. To demonstrate the same, we used both the int 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))
Smallest Number in an Array using sort()
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])
[99, 14, 150, 11, 184, 5, 190]
<class 'numpy.ndarray'>
5
Python Program to Find Smallest Number in an Array using for loop
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)
[14, 27, 99, 10, 50, 65, 18, 4, 195, 100]
The Smallest Number = 4
The Index Position = 7