Skip to content

Write a Python program to get the smallest number from a list | Example code

  • by

Using the min() function, you can easily write a Python program to get the smallest number from a list. You can also do list sorting and get the first element in the list.

Python program to get the smallest number from a list

A simple example code gets the smallest number from a list.

list1 = [10, 20, 100, 40, 90]

res = min(list1)

print("Smallest number is:", res)

Output:

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

Another way is by sorting the list

Sort the list in ascending order and the first element in the list will be the smallest number. The list index starts from 0, so the first element will be list[0].

list1 = [10, 20, 100, 40, 90]

list1.sort()

print(list1[0])

Output: 10

Using for loop with a custom function

list1 = [10, 20, 100, 40, 90]


def small_num(list):
    min = list[0]
    for a in list:
        if a < min:
            min = a
    return min


res = small_num(list1)

print(res)

Using a loop:

def find_smallest_number(numbers):
    if not numbers:
        return None  # Handle an empty list
    smallest = numbers[0]  # Initialize with the first element
    for num in numbers:
        if num < smallest:
            smallest = num
    return smallest

# Example usage:
my_list = [5, 2, 9, 1, 7]
smallest_number = find_smallest_number(my_list)
print("The smallest number is:", smallest_number)

Using the min() function:

def find_smallest_number(numbers):
    if not numbers:
        return None  # Handle an empty list
    return min(numbers)

# Example usage:
my_list = [5, 2, 9, 1, 7]
smallest_number = find_smallest_number(my_list)
print("The smallest number is:", smallest_number)

Both approaches will give you the smallest number in the list. The min() function is more concise and efficient, so it’s generally recommended for this task.

Do comment if you have any doubts or suggestions on this Python List topic.

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