Javaexercise.com

How To Find Largest Number In The Python Lists?

In this article, we are going to see how we can find the largest number present in the list. Let's understand the topic with the help of simple examples.

For Examples:

Input: [22, 53, 75, 64, 24]
Output: 75
​
Input: [54, 23, 18, 83, 66]
Output: 83

The different ways to find out the largest element present in the list are:

  1. Using sort() method

  2. Using max() method

  3. Without using built-in functions

Find largest element in the list using sort() method

In this approach, we sort the list of numbers in ascending order with the help of the sort() method and then we print the element present at last in the list.

Algorithm:

Step 1: Create a list of numbers

Step 2: Use the sort() method to sort the list in ascending order

Step 3: Print the last element of the list

See the below Python code implementation of the above algorithm.

# Python program to find the largest
# number in a list using sort()
​
# list of the numbers
list1 = [15, 64, 34, 74, 18]
​
# sorting the list
list1.sort()
​
# printing the last element
print("The largest element is:", list1[-1])

Output:

The largest element is: 74

Find the largest element in the list using the max() method

Algorithm:

Step 1: Create a list of numbers

Step 2: Use max() method

Step 3: Print that maximum number

See the below Python code implementation of the above algorithm.

# Python program to find the largest
# number in a list using max()
​
# list of the numbers
list2 = [15, 64, 34, 74, 18]
​
# printing the maximum element
print("The largest element is:", max(list2))

​Output:

The largest element is: 74

Find the largest element in the list without using for loop

Algorithm:

Step 1: Define a function that will find the largest number

Step 2: Declare the variable that will store the largest number

Step 3: Set the value of the variable to the first element of the list

Step 4: Create a for loop

Step 5: Compare each element with the variable which stores the smallest value

Step 6: If the element is larger than the value in the variable then set that element as the value of the variable

Step 7: Return the variable

Step 8: Create a list

Step 9: Call function and print the output

See the below Python code implementation of the above algorithm.

# Python program to find largest
# number in a list without using built-in functions

def myLar(list1):

    # Assume the first number in the list is largest
    # initially and assign it to variable "lar"
    lar = list1[0]

    # Now traverse through the list and compare
    # each number with "lar" value. Whichever is
    # largest assign that value to "lar'.
    for x in list1:
        if x > lar:
            lar = x

    # after complete traversing the list
    # return the "lar" value
    return lar


# Driver code
list1 = [15, 64, 34, 74, 18]
print("Largest element is:", myLar(list1))

Output:

Largest element is: 74