In this section of python programming, we will understand the different methods to find the largest number in the list.
list = [1, 2, 3, 7, 5, 9, 12, 10, 4] #Using loop def largest(list): max = 0 for i in list: if max < i: max = i return max print("Largest number using loop: ",largest(list)) #Using sort() list.sort() print("Largest number using sort()",list[-1]) #Using max() larg_result = max(list) print("Largest number using max(): ",larg_result)
In the above python code we have used loop, sort() and max() to find the largest number in the list. In loop, we have assigned the max to zero and check max against each element in the list. If the element is greater than the max, the value is assigned to max and the loop continues till the maximum number is found.
Using sort(), we have sorted the list in ascending order and taken the element from right (index -1 for rightmost element).
The max() function directly finds the maximum number in the list and returns the result.