How to find the largest and smallest number in a Python list
Published on Aug. 22, 2023, 12:16 p.m.
To find the largest and smallest number in a Python list
To find the largest and smallest number in a Python list, you can use the built-in max()
and min()
functions, respectively. Here’s an example code:
my_list = [1, 2, 3, 4, 5]
largest_num = max(my_list)
smallest_num = min(my_list)
print("The largest number in the list is:", largest_num)
print("The smallest number in the list is:", smallest_num)
In this code, we define a list called my_list
containing some integers. We then use the max()
and min()
functions to find the largest and smallest numbers in the list, respectively. We store these values in variables called largest_num
and smallest_num
, respectively. Finally, we print out the largest and smallest numbers in the list using the print()
function.
If the list contains strings or other non-numeric elements, the max()
and min()
functions will still work, but they will return the largest and smallest elements based on the ASCII values of the characters. If you want to find the largest and smallest numbers in a list of mixed data types, you may need to use conditional statements and convert the elements to numeric data types before comparing them.
To find the largest and smallest numbers in Python without using a list
To find the largest and smallest numbers in Python without using a list, you can simply use the max()
and min()
functions with individual numeric values. Here’s an example code:
num1 = 10
num2 = 5
num3 = 20
largest_num = max(num1, num2, num3)
smallest_num = min(num1, num2, num3)
print("The largest number is:", largest_num)
print("The smallest number is:", smallest_num)
In this code, we define three numeric variables num1
, num2
, and num3
. We then use the max()
and min()
functions to find the largest and smallest numbers among these three values. We store these values in variables called largest_num
and smallest_num
, respectively. Finally, we print out the largest and smallest numbers using the print()
function.
You can apply the same logic to find the largest and smallest values among any number of individual numeric values.