Python Program to Find Largest Number in a List (original) (raw)

Last Updated : 21 Oct, 2024

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.

Python `

a = [10, 24, 76, 23, 12]

Max() will return the largest in 'a'

largest = max(a) print(largest)

`

**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).

Python `

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)

`

Another method to find the largest number in a list is by using the **reduce() function along with a lambda expression.

Python `

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)

`

**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:

Which method to choose?

**Related Articles:

Similar Reads