Python Program to Find Largest Number in a List

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)
Run Code Copy

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)
Run Code Copy

Output

Largest element is: 52

In this example, we have assumed a list and initialized largest number ln variable to the first element of the list. If there are no elements in the list, ln is initialized with None.

Iterate the loop for each element in the list. During each iteration, we check if the largest number is less than this element. If that is the case, we update our largest number with the element.

When you complete traversing the list, you will end up with the largest number of the list in your variable.

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.

Related Tutorials

Code copied to clipboard successfully 👍