Python Program to Find Largest Number in an Array

Write a Python Program to Find the Largest Number in an Array. The numpy module has a max function that returns an array’s maximum value. We use this numpy function to return the maximum item in a number 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 1

Python Program to Find Largest Number in an Array

We used the numpy sort function to sort the array in ascending order and print the number at the last index position, which is the largest.

import numpy as np
lgtarr = np.array([50, 15, 22, 270, 199, 195, 100])

lgtarr.sort()
lgtlength = len(lgtarr) - 1

print(lgtarr[lgtlength])
270

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 if condition (if(largest < lgtarr[I])) examines whether the current 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   =  1750
Index Position =  5