How To Find The Largest And Smallest Numbers In Python? - Python Guides (2024)

Recently, while working with lists or arrays of numbers in Python, I had one requirement: find the minimum and maximum values. Python provides a few easy ways to get this. In this tutorial, I will explain different methods to find the largest and smallest numbers in Python with examples.

To find the largest and smallest number in a list in Python, you can use the built-in functions max() and min(). For example, if you have a list numbers = [3, 1, 4, 1, 5, 9, 2], you can find the largest number by calling max(numbers) and the smallest number by calling min(numbers). These functions efficiently return the maximum and minimum values from the list, respectively.

# Example list of numbersnumbers = [3, 1, 4, 1, 5, 9, 2]# Finding the largest numberlargest_number = max(numbers)# Finding the smallest numbersmallest_number = min(numbers)# Printing the resultsprint("The largest number is:", largest_number)print("The smallest number is:", smallest_number)

Table of Contents

Find the Largest and Smallest Numbers in Python

Now, let me show you how to find the largest and smallest numbers in Python using different methods:

1. Using the min() and max() Functions

Python has built-in min() and max() functions that allow you to easily find the smallest and largest values in a list or array. Here’s how to use them:

numbers = [28, 56, 42, 10, 95, 73]smallest = min(numbers)largest = max(numbers)print(f"The smallest number is: {smallest}") print(f"The largest number is: {largest}")

Output:

The smallest number is: 10The largest number is: 95

The min() and max() functions are the simplest way to find the extremes in a list. They work by iterating through the list and keeping track of the current minimum and maximum values encountered.

You can see the output in the screenshot below after I executed the above Python code using VS code.

How To Find The Largest And Smallest Numbers In Python? - Python Guides (1)

Check out Sum of Digits of a Number in Python

2. Using a For Loop

Another way to find the largest and smallest numbers in Python in a list is by using a for loop to iterate through each element. Here’s how it works:

numbers = [28, 56, 42, 10, 95, 73]smallest = largest = numbers[0]for num in numbers: if num < smallest: smallest = num if num > largest: largest = numprint(f"The smallest number is: {smallest}")print(f"The largest number is: {largest}")

Output:

The smallest number is: 10The largest number is: 95

In this approach, we initialize both smallest and largest to the first element of the list (numbers[0]). Then, we use a for loop to iterate through each number in the list. For each number, we check if it is smaller than the current smallest or larger than the current largest. If so, we update the corresponding variable.

After the loop finishes, smallest will hold the minimum value, and largest will hold the maximum value from the list.

You can see the output in the screenshot below:

How To Find The Largest And Smallest Numbers In Python? - Python Guides (2)

Check out Write a Python Program to Divide Two Numbers

3. Using a While Loop

You can also use a while loop to find the largest and smallest numbers in a list by repeatedly prompting the user for input until a specific condition is met. Here’s an example:

numbers = []while True: user_input = input("Enter a number (or 'done' to finish): ") if user_input == 'done': break numbers.append(int(user_input))if len(numbers) > 0: smallest = largest = numbers[0] i = 1 while i < len(numbers): if numbers[i] < smallest: smallest = numbers[i] if numbers[i] > largest: largest = numbers[i] i += 1 print(f"The smallest number is: {smallest}") print(f"The largest number is: {largest}")else: print("No numbers were entered.")

Sample Output:

Enter a number (or 'done' to finish): 42Enter a number (or 'done' to finish): 17Enter a number (or 'done' to finish): 99Enter a number (or 'done' to finish): 28Enter a number (or 'done' to finish): doneThe smallest number is: 17The largest number is: 99

In this approach, we start with an empty list called numbers. We use a while loop with a True condition to repeatedly prompt the user for input. If the user enters ‘done’, we break out of the loop. Otherwise, we append the user’s input (converted to an integer) to the numbers list.

After collecting the user’s input, we check if the numbers list has any elements. If it does, we initialize smallest and largest to the first element of the list (numbers[0]). We then use another while loop to iterate through the remaining elements of the list, starting from index 1. For each element, we compare it with the current smallest and largest values and update them accordingly.

Here is the output in the screenshot below:

How To Find The Largest And Smallest Numbers In Python? - Python Guides (3)

Read How to Format Numbers with Commas in Python?

Find the Second Smallest and Second Largest

Sometimes, you may want to find the second smallest or second largest values in a list. To do this, you can:

  1. Usemin()andmax()to find the smallest and largest elements
  2. Remove those elements from the list usinglist.remove()
  3. Callmin()andmax()again on the modified list

Here’s an example:

numbers = [28, 56, 42, 10, 95, 73]smallest = min(numbers)largest = max(numbers)numbers.remove(smallest) numbers.remove(largest)second_smallest = min(numbers)second_largest = max(numbers)print(f"The second smallest number is: {second_smallest}")print(f"The second largest number is: {second_largest}") 

Output:

The second smallest number is: 28The second largest number is: 73

Conclusion

Python’s min() and max() functions provide a quick and easy way to find the smallest and largest values in a list or array. You can also use these functions along with list.remove() to find the second smallest and second largest values if needed. In this tutorial, I have explained how to find the largest and smallest numbers in Python with examples.

You may also like:

  • Check if a Variable is Between Two Numbers in Python
  • Write a Program to Add Two Numbers Using Functions in Python
  • How to Check if a Variable is a Number in Python?

How To Find The Largest And Smallest Numbers In Python? - Python Guides (4)

Bijay Kumar

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

How To Find The Largest And Smallest Numbers In Python? - Python Guides (2024)
Top Articles
Welfare Check (What It Is And How It Works: Explained)
Modelo de certificado de trabajo para presentar en el colegio
탱글다희 Fantrie
Absence & Substitute Management - Part of Frontline Absence & Time
Amwednesday Vimeo
Number One Buffet Ravenna
Section 104 Capital One Arena
Acchs Sapphire
Creed 3 Showtimes Near Southeast Cinemas Alamance Crossing Stadium 16
ZQuiet Anti-Snoring Mouthpiece Review 2024 - Sleep Doctor
Sandals Travel Agent Login
Nier: Automata - How to Get All Endings
Ylennoir
Prettyaline
Howmet Upoint Login
Pronomic CM-22 Test - homerecording-forum.de
Lubbock Avalanche Journal Newspaper Obituaries
John Deere S100 Vs Cub Cadet Xt1
Elsenpeter Auctions Monticello Mn
Polyhaven Hdri
Decree Of Spite Poe
Unraid Delete Share
Aaa Saugus Ma Appointment
Beauty Supply Store Clinton Nc
Angel Nails Texarkana
Boulangerie Suffren 55
Primepoint Business Access
Dit zijn de 14 beste restaurants van Amsterdam
Craigslist For Cleveland Ohio
Realidades 2 Capitulo 2B Answers
Cerro Gordo Property Search Beacon
Nbstsa Verification
Newadvent Org
2003 Chevrolet Corvette Z06 Coupe On for sale - Portland, OR - craigslist
Das ist DIE Lösung für Homestudios & Producer
Monkey Flask Review 2022
Costco Gas Prices Sioux Falls
Oakley Rae Net Worth – Real Name, Wiki, Husband, Age, Height
Alylynn
Excel Module 4 Sam End Of Module Project 2
Ticket To Paradise Showtimes Near Regal West Manchester
Breindy Active Fitness
St Edwards Bloomington Mn
Uncutmazaa
Best Engineer Build Deep Rock Galactic
Kobalt Kst 180-06 Parts
Holly Ranch Aussie Farm
What Is The Factored Form Of The Polynomial 27X2Y-43Xy2
25 Best Manga You Can Read Right Now
Rutgers University-RUWirelessSecure | Powered by SecureW2
Admin - Space Station 13 Wiki
Cl Bellingham
Latest Posts
Article information

Author: Kieth Sipes

Last Updated:

Views: 6522

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.