Calculate Sum Get User Input Patterns Program Find Area of CircleFind Area of Rectangle Perimeter of Rectangle Find Even and Odd Numbers Find Sum of Digit in Python Find Factorial in PythonPrint Fibonacci Series Check Armstrong Number Reverse a Number Check Palindrome Number Swap Two Numbers Matrix MultiplicationFind Perfect NumberAdd Two Matrix in Python Find Sum of Squares Find Sum of Cubes Find URL in String
Find Largest in List Find Duplicate in List Check Alphabet Remove Duplicate Elements from List Reverse List Elements Find Element in Python List Interchange first and last element in List Find Even Numbers in List Find Length of a List Find Sum of list Elements Find Elements in List Get the product of List elements Interchange List Elements Find Smallest Elements in List Find Max Value in a List
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.
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 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
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 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