Skip to content

Write a Python program to get the largest number from a list | Code

  • by

You can use your own logic to compare each item of the list using a for loop to get the largest number from a list in Python. Or use the max() function in the build function in Python.

Python program to get the largest number from a list

Simple example code has a list of numbers and the task is to write a Python program to find the largest number in the given list.

Without using built-in functions

def max_num(lst):
    m = lst[0]
    for a in lst:
        if a > m:
            m = a
    return m


print(max_num([1, 2, -1, 0]))

Output:

Write a Python program to get the largest number from a list

Using max() method

list1 = [10, 20, 4, 45, -99]

# printing the maximum element
print("Largest element is:", max(list1))

Output: Largest element is: 45

Using sort method

Sort the list in ascending order and print the last element in the list.

list1 = [10, 20, 4, 45, 99]

list1.sort()

# printing the last element
print(list1[-1])

Output: 99

Here’s a simple Python program that takes a list of numbers as input and returns the largest number from that list:

def get_largest_number(numbers):
    if not numbers:
        return None  # Return None for an empty list

    largest = numbers[0]
    for num in numbers:
        if num > largest:
            largest = num

    return largest

# Example usage
num_list = [12, 45, 6, 78, 23, 56]
largest_num = get_largest_number(num_list)
print("The largest number is:", largest_num)

Replace the num_list variable with your own list of numbers to find the largest number in your desired list.

Do comment if you have any doubts or suggestions on this Python program code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading