Python program to find largest number present in a list
Consider below is the input list, where you want to find the largest number of a list.
arr = [1000, 100, 10000, 10]
You should get output as 10000 which is the largest number.
1. Python program to find the largest number of an list using max() function
inp = [1000, 100, 10000, 10]; # initialize list
def largestArrElement(arr) :
mx = arr[0]; # initialize mx with first element of the list
n = len(arr);
for i in range(1, n):
if arr[i] > mx: # compare every element of the list with mx and then assign largest num to mx
mx = arr[i]
return mx
maxNum = largestArrElement(inp)
print ("Largest number of the list: ", maxNum)
Run here
In the above program,
- we have initialized the list with the input and
mx
variable with first element of the list - Using for loop we are traversing list from second element to the length of the list
- Then we are comparing every element present in the list with the first element and then assigning the larger value to
mx
variable - Returning the largest value from the function and then printing it in the main program
Results
Largest number of the list: 10000
2. Python program to find the largest number of a list using sort()
inp = [1000, 100, 10000, 10] # initialize list
inp.sort() # sorting the list items in ascending order
# printing last element of the list as it the largest after sorting
print ("Largest number of the list: ", inp[-1])
Run here
In the above program, we are using sort() function to sort the elements of the list in an ascending order. Hence, largest number will be last element present in the list.
Results
Largest number of the list: 10000