Python Program to Find Largest Number in a List
Finding the largest number in a list is a common task in Python. There are multiple way to do but the simplest way to find the largest in a list is by using Python’s built-in max() function:
Using max()
Python provides a built-in max() function that returns the largest item in a list or any iterable. The time complexity of this approach is O(n) as it traverses through all elements of an iterable.
a = [10, 24, 76, 23, 12]
# Max() will return the largest in 'a'
largest = max(a)
print(largest)
Output
76
Explanation: max(a): This function takes the list ‘a’ as input and returns the largest value.
Now, let’s explore other methods to find maximum in a list.
Table of Content
Using a Loop (Native method)
If we want to find the largest number in a list without using any built-in method (i.e. max()) function then can use a loop (for loop).
a = [10, 24, 76, 23, 12]
# Assuming first element is largest.
largest = a[0]
# Iterate through list and find largest
for val in a:
if val > largest:
# If current element is greater than largest
# update it
largest = val
print(largest)
Output
76
Using reduce() function from functools
Another method to find the largest number in a list is by using the reduce() function along with a lambda expression.
from functools import reduce
a = [10, 24, 76, 23, 12]
# Find the largest number using reduce
largest = reduce(lambda x, y: x if x > y else y, a)
print(largest)
Output
76
Explanation: reduce(lambda x, y: x if x > y else y, a): The reduce() function takes pairs of elements in the list a and applies the lambda function to return the largest value. The lambda function compares x and y and returns the larger of the two.
Using sort()
The sort() method is one of the quick method to get the largest value from list but this approach has a higher time complexity (O(n log n)) compared to using max() which is O(n) time.
a.sort()
largest = a[-1]
Explanation:
- a.sort(): This sorts the list a in ascending order.
- a[-1]: The largest number is the last element in the sorted list.
Which method to choose?
- Using max(): This is easiest and most recommended way.
- Using a Loop: This method is good if we want to solve manually.
- Using reduce(): An advanced option for those interested in functional programming.
- Using sort(): This method is not recommended here due to its higher time complexity.
Related Articles:
- Find positions of maximum element in list in Python
- Maximum and Minimum value from two lists
- Find the maximum and minimum element in a NumPy array
- Elements Maximum till current index in List