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
Korn - Y'All Want a Single Lyrics
The Makers and Teachers of Judaism&#10;From the Fall of Jerusalem to the Death of Herod the Great
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
Red Dead Redemption 2 Legendary Fish Locations Guide (“A Fisher of Fish”)
What's the Difference Between Halal and Haram Meat & Food?
R/Skinwalker
Rugged Gentleman Barber Shop Martinsburg Wv
Jennifer Lenzini Leaving Ktiv
Justified - Streams, Episodenguide und News zur Serie
Epay. Medstarhealth.org
Olde Kegg Bar & Grill Portage Menu
Cubilabras
Half Inning In Which The Home Team Bats Crossword
Amazing Lash Bay Colony
Juego Friv Poki
Dirt Devil Ud70181 Parts Diagram
Truist Bank Open Saturday
Water Leaks in Your Car When It Rains? Common Causes & Fixes
What’s Closing at Disney World? A Complete Guide
New from Simply So Good - Cherry Apricot Slab Pie
Drys Pharmacy
Ohio State Football Wiki
Find Words Containing Specific Letters | WordFinder®
FirstLight Power to Acquire Leading Canadian Renewable Operator and Developer Hydromega Services Inc. - FirstLight
Webmail.unt.edu
2024-25 ITH Season Preview: USC Trojans
Metro By T Mobile Sign In
Restored Republic December 1 2022
12 30 Pacific Time
Jami Lafay Gofundme
Greenbrier Bunker Tour Coupon
No Compromise in Maneuverability and Effectiveness
Black Adam Showtimes Near Cinemark Texarkana 14
Teamnet O'reilly Login
U-Haul Hitch Installation / Trailer Hitches for Towing (UPDATED) | RV and Playa
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 5795

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.