Javaexercise.com

How to Find Largest Number From a List in Python

This article is about finding the largest elements in a Python list. To find the largest elements, there can be several ways such as the max() method, or custom code that includes loops and other built-in methods like sorted(). Let's see some examples. 

Algorithm To Find Largest Number in Python List

Step 1: Take a list as input

Step 2: Create a variable max_val and initialize it to zero

Step 3: Iterate a loop for all the values in the list

Step 4: Check if the value is greater than max_val then assign it to the max_val variable

Step 5: Repeat step 3 and 4 until the loop exits

Step 6: Display the found max value

 

Python Program to Find the Largest Number in List using max() Method

Python provides built-in method max() that can be used to find the largest element in the list. Here, we used this method to find the maximum element present in the list. See the code example and output.

# Take a list
list1 = [12,32,54,12,6,8,11]
print(list1)
# Fetch maximum from the list
max_val = max(list1)
# Display result
print("maximum: ", max_val)

Output:

[12, 32, 54, 12, 6, 8, 11]

maximum:  54

 

Python Program to Find the Largest Number in List

If we don't want to use a built-in method such as max() then we can use this custom code to find the largest element from the list. This example uses a loop and if condition to find the largest element in the list. See the code and output.

# Take a list
list1 = [12,32,54,12,6,8,11]
print(list1)
# Fetch maximum from the list
max_val = 0
for i in list1:
    if i > max_val:
        max_val = i
# Display result
print("maximum: ", max_val)

Output:

[12, 32, 54, 12, 6, 8, 11]

maximum:  54

 

Python Program to Find the Largest Number in List using sorted() Method

Python sorted() method is used to sort iterable like list, tuple, etc. Here, we are using it to sort list elements and then fetch the largest element. By default this method sort elements into ascending order but if we pass reverse=True as an argument then it will sort elements into descending order that makes our task easy and we can fetch the largest elements by referring to the first index of the list. See the code example and output below. 

# Take a list
list1 = [12,32,54,12,6,8,11]
print(list1)
# Fetch maximum from the list
max_val = sorted(list1,reverse=True)
# Display result
print("maximum: ", max_val[0])

Output:

[12, 32, 54, 12, 6, 8, 11]

maximum:  54