Python Code Example: Smallest and Largest Number in List

In this Python tutorial, we will learn how to find the smallest and largest numbers in a list. The min() and max() functions in Python make it simple to find the minimum and maximum values in a list of numbers. We will write a Python program that uses these functions to identify the smallest and largest numbers in a list. This is a common operation when working with numerical data, helping us quickly assess the range of values in a list.

Code Example

# List of numbers
numbers = [10, 25, 3, 40, 12, 7, 50]

# Finding the smallest and largest numbers
smallest_number = min(numbers)  # Find the smallest number
largest_number = max(numbers)  # Find the largest number

# Output the results
print("Smallest number:", smallest_number)
print("Largest number:", largest_number)

Output

Smallest number: 3
Largest number: 50

Code Explanation

  1. List of Numbers: We define a list of numbers: [10, 25, 3, 40, 12, 7, 50].
  2. Finding the Smallest Number: We use Python’s built-in min() function to find the smallest number in the list. This function scans through the list and returns the element with the lowest value.
  3. Finding the Largest Number: Similarly, the max() function is used to find the largest number in the list. This function scans the list and returns the element with the highest value.
  4. Output: We print the results, displaying both the smallest and largest numbers found in the list.

This code demonstrates how to efficiently use Python’s built-in functions to find the smallest and largest numbers in a list, making it easy to analyze a set of values.