Learnitweb

Python program to find largest number in a list

We’ll discuss 3 methods to find largest number in a list.

Method 1 : Sort the list in ascending order and print the last element in the list.

#input list
inputList = [10, 20, 9, 4, 12, 11, 3]

#sort the list
inputList.sort()

#get the last element of the list and print
result = inputList[-1]
print("largest number in the list is: ", result)

Output

largest number in the list is:  20

Method 2 : Using max() method

#input list
inputList = [10, 20, 9, 4, 12, 11, 3]

#get the largest element using max() method
result = max(inputList)
print("largest number in the list is: ", result)

Output

largest number in the list is:  20

Method 3: Without using built in functions

def getMax(inputList): 
  
    # Assume and initialize first number in list as largest
    # max variable used to hold largest number  
    max = inputList[0] 
   
    # Traverse through the list and compare  
    # each number with "max" value. If another
    # max number found, assign that number to "max"  
    for x in inputList: 
        if x > max : 
             max = x 
    
    # return max
    return max
  
# code to call getMax() to find largest number 
inputList = [10, 20, 9, 4, 12, 11, 3]
print("Largest element is:", getMax(inputList))

Output

Largest number in list is: 20