How to find Largest Number of a List in Python?


Find Largest Number in Python List

You can find largest number of a list in Python using sort() function or more basic for loop.

Python Find Largest Number in List

Using sort() function is kind of concise, but using For Loop is efficient. We will go through these two approaches with examples.


Examples

1. Find the largest number in given list using sort()

We know that sort() builtin function sorts a list in ascending or descending order. After you sort a list, you have your largest number at the end of the list if you have sorted in ascending order or at the start of the list if you have sorted in descending order.

In the following example, we will sort the given list in ascending order. Of course, last number of the sorted list is our required largest number.

Python Program

# list
a=[18, 52, 23, 41, 32]

# sort the list, default is in ascending order
a.sort()

# largest number is the last item in the sorted list
ln = a[-1]

# print the largest number
print("Largest element is: ",ln)

Explanation

  1. A list a is initialized with the elements [18, 52, 23, 41, 32].
  2. The sort() method is called on the list a, which arranges the elements in ascending order. The sorted list becomes [18, 23, 32, 41, 52].
  3. The largest number in the list is the last element, which can be accessed using the index -1. This value is stored in the variable ln.
  4. The print() function is used to display the largest element with the message "Largest element is:". The output is Largest element is: 52.

Output

Largest element is: 52

a[-1] fetches the last element in the list.


2. Find largest number in list using For loop

Though finding the largest number using sort() function is easy, using Python For Loop does it relatively faster with less number of operations. Also, the contents of the list are unchanged.

Python Program

a = [18, 52, 23, 41, 32]

#variable to store largest number
ln = a[0] if a else None

#find largest number
for i in a:
	if i>ln:
		ln=i

print("Largest element is: ",ln)

Explanation

  1. A list a is initialized with the elements [18, 52, 23, 41, 32].
  2. The variable ln is initialized to the first element of the list, a[0], if the list is not empty. If the list is empty, ln is set to None.
  3. A for loop is used to iterate through each element i in the list a.
  4. Inside the loop, an if statement checks if the current element i is greater than ln. If true, ln is updated to i.
  5. At the end of the loop, ln contains the largest number in the list.
  6. The print() function is used to display the largest element with the message "Largest element is:". For the given list, the output is Largest element is: 52.

Output

Largest element is: 52

Summary

In this tutorial of Python Examples, we learned some of the ways to find largest number in Python list with the help of well detailed Python example programs.


Python Libraries