Editor

Python Program to Find the Largest and Smallest Number in a List

Beginner · Lists · CBSE class 11 practical list

This program finds the largest and the smallest number in a list without using the built-in max() and min() functions. It walks through the list once and remembers the biggest and smallest values it has seen so far.

Program

largest_smallest_in_list.py
numbers = [34, 12, 89, 5, 67, 23] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
# Start with the first element as both the largest and the smallest
largest = numbers[0]
smallest = numbers[0]
for num in numbers:
if num > largest:
largest = num
if num < smallest:
smallest = num
print("List:", numbers)
print("Largest number:", largest)
print("Smallest number:", smallest)
Output
List: [34, 12, 89, 5, 67, 23]
Largest number: 89
Smallest number: 5

How it works

  1. largest and smallest both start as the first element, numbers[0].
  2. The loop compares every number with them and updates whichever one it beats.
  3. After one pass over the list, largest and smallest hold the answers.
  4. Starting from numbers[0] rather than 0 means the program still works when every number is negative.

Another way to write it

Using max() and min()

Using max() and min()
numbers = (34, 12, 89, 5, 67, 23) # a tuple works the same way
print("Largest number:", max(numbers))
print("Smallest number:", min(numbers))
print("Largest is at index", numbers.index(max(numbers)))
print("Smallest is at index", numbers.index(min(numbers)))
Output
Largest number: 89
Smallest number: 5
Largest is at index 2
Smallest is at index 3

The built-in functions work on lists and tuples alike, and index() tells you where each value sits.

Try it yourself

Change the list to [-4, -15, -2, -9] and check that the answers are still right.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises