Python Program to Find Largest Number in a List
Given a list of numbers, the task is to find the largest number in the list. For Example:
Input: [10, 24, 76, 23, 12]
Output: 76
Below are the different methods to perform this task:
Using max() Function
The max() function compares all elements in the list internally and returns the one with the highest value.
a = [10, 24, 76, 23, 12]
res = max(a)
print(res)
Output
76
Using reduce() from functools
Applies a function cumulatively to the list elements to compute a single result, here used to find the largest number.
from functools import reduce
a = [10, 24, 76, 23, 12]
res = reduce(lambda x, y: x if x > y else y, a)
print(res)
Output
76
Explanation: reduce(lambda x, y: x if x > y else y, a) compares each pair of elements in the list a and keeps the larger one, cumulatively returning the maximum value.
Using a Loop
A native approach that iterates through the list and updates a variable if a larger number is found.
a = [10, 24, 76, 23, 12]
res = a[0]
for n in a:
if n > res:
res = n
print(res)
Output
76
Explanation: Each element is compared to the current largest, and the variable is updated when a bigger number is found.
Using sort()
Sorts the list in ascending order so that the largest element can be accessed at the end.
a = [10, 24, 76, 23, 12]
a.sort()
res = a[-1]
print(res)
Output
76