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.
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
- A list
a
is initialized with the elements[18, 52, 23, 41, 32]
. - The
sort()
method is called on the lista
, which arranges the elements in ascending order. The sorted list becomes[18, 23, 32, 41, 52]
. - The largest number in the list is the last element, which can be accessed using the index
-1
. This value is stored in the variableln
. - The
print()
function is used to display the largest element with the message"Largest element is:"
. The output isLargest 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
- A list
a
is initialized with the elements[18, 52, 23, 41, 32]
. - 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 toNone
. - A
for
loop is used to iterate through each elementi
in the lista
. - Inside the loop, an
if
statement checks if the current elementi
is greater thanln
. If true,ln
is updated toi
. - At the end of the loop,
ln
contains the largest number in the list. - The
print()
function is used to display the largest element with the message"Largest element is:"
. For the given list, the output isLargest 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.