In this tutorial, we will see various Python programs to find the largest number in a List. For example, if the list is [5, 10, 30, 6] then the output of the program should be 30 (the largest number in the given list).
Example 1: Finding largest number in a list using sort() method
In the following program we are using the sort() function to find the largest number in the given list. A list of numbers is given in the program and we are sorting the given list using sort() function, which sorts the list in ascending order. We are then displaying the last element of the list, which is the largest number in the sorted list.
# Python program to find largest number in a list # A list of numbers is given lis = [1, 10, 40, 36, 16] # sorting the given list "lis" # sort() function sorts the list in ascending order lis.sort() # Displaying the last element of the list # which is the largest number in the sorted list print("Largest number in the list is:", lis[-1])
Output:
Example 2: Finding largest number in a list using max() method
In the following program we are finding the largest number of the list using max() method. The max() method returns the largest element of the list.
# Python program to find largest number in a list # using max() function # A list of numbers lis = [19, 10, 45, 26, 6] # max() method returns the largest element of the list print("Largest number of the list is:", max(lis))
Output:
Example 3: Finding largest number in a list, where list is provided by user
In the following example we are finding the largest number in the user provided list. In the program, user is asked to enter the number of elements to put in a list, then user enters the elements of the list which are appended to the list using append() method. At the end the largest element is displayed using max() method.
# creating empty list lis = [] # user enters the number of elements to put in list count = int(input('How many numbers? ')) # iterating till count to append all input elements in list for n in range(count): number = int(input('Enter number: ')) lis.append(number) # displaying largest element print("Largest element of the list is :", max(lis))
Output:
Leave a Reply