Python program to find largest and smallest number in a list
Description: Write a Python program to find the largest and the smallest number in a list.
Rules and hints:
- First use the built-in
max()andmin()functions. - Then do it with a loop, without these functions.
Python program to find the largest and smallest number in a list
numbers = [45, 12, 89, 3, 67]
print("Largest:", max(numbers))
print("Smallest:", min(numbers))
largest = smallest = numbers[0]
for n in numbers:
if n > largest:
largest = n
if n < smallest:
smallest = n
print("Loop result:", largest, smallest)
Output:
Tutorials Class - Output Window
Largest: 89
Smallest: 3
Loop result: 89 3
How it works
max()andmin()check the whole list for you.- In the loop we start with the first item as both largest and smallest, and update them when a bigger or smaller item comes.
Learn more in Python Lists.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |