Write a Python Program to Find the Largest Number in an Array using the for loop, built-in max(), sort(), and len() functions.
The numpy module has a Python NumPy max function that returns an array’s maximum value. This numpy function returns the maximum item in a numeric and string array.
import numpy as np
lgtarr = np.array([50, 65, 14, 27, 99, 10, 4, 195, 18, 100])
print("Numeric Largest Numpy Array Items = ", lgtarr)
print("The Largest Number in this Numpy Array = ", max(lgtarr))
strlgtarr = np.array(['UK','India', 'Japan', 'USA'])
print("String Largest Numpy Array Items = ", strlgtarr)
print("The Largest Number in this Numpy Array = ", max(strlgtarr))

Python Program to Find Largest Number in an Array using sort and len
We used the Python sort function to sort the NumPy array in ascending order and print the number at the last index position, which is the largest. For more examples, refer to the Python Basic Programs.
import numpy as np lgtarr = np.array([50, 15, 22, 270, 199, 195, 100]) lgtarr.sort() lgtlength = len(lgtarr) - 1 print(lgtarr[lgtlength])
270
Largest Number in an Array using For Loop
In this example, we assigned the first value as the largest, and the for loop range starts at one and traverses uptown lgtarr length minus.
The Python if condition (if(largest < lgtarr[I])) examines whether the current Python NumPy array element is less than the largest. If True, assign that value to the largest variable and the index value to the larposition variable (larposition = i).
import numpy as np
lgtarr = np.array([270, 199, 220, 195, 1200, 1750, 100])
largest = lgtarr[0]
for i in range(1, len(lgtarr)-1) :
if(largest < lgtarr[i]) :
largest = lgtarr[i]
larposition = i
print("Largest = ", largest)
print("Index Position = ", larposition)
Largest = 750
Index Position = 5
Also Read
- Python program to Count Positive and Negative Numbers in an Array
- Python program to find Length of a NumPy Array