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.
Example 1: Find the largest number using sort() function
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.
# 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)
Largest element is: 52
a[-1] fetches the last element in the list.
Example 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.
a = [18, 52, 23, 41, 32] #variable to store largest number ln = a if a else None #find largest number for i in a: if i>ln: ln=i print("Largest element is: ",ln)
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.
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 – Check if Element is in List
- Python List of Lists
- Python List without Last Element
- Python – Traverse List except Last Element
- How to Check if Python List is Empty?
- How to Reverse Python List?
- How to Access List Items in Python?
- Python – Check if List Contains all Elements of Another List
- Python – Get Index or Position of Item in List
- How to Get List of all Files in Directory and Sub-directories?