To find the largest and smallest numbers in a list
Expt. No.08
Page No.16
Largest and smallest in a list
Aim
To write a Python program that inputs numbers into a list and finds the largest and smallest numbers, with a loop and with max() and min().
Concepts used
Algorithm
- Input how many numbers and append each to a list.
- Take the first element as both largest and smallest; compare every element to update them.
- Display the results, and check them with max() and min().
Program
# Largest and smallest numbers in a list nums = []n = int(input("How many numbers? "))for i in range(n): nums.append(int(input("Enter a number: "))) largest = nums[0]smallest = nums[0]for x in nums: if x > largest: largest = x if x < smallest: smallest = xprint("List :", nums)print("Largest (loop) :", largest, " max():", max(nums))print("Smallest (loop):", smallest, " min():", min(nums))
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python largest_smallest_in_list.py
How many numbers? 6
Enter a number: 45
Enter a number: 12
Enter a number: 78
Enter a number: -3
Enter a number: 56
Enter a number: 30
List : [45, 12, 78, -3, 56, 30]
Largest (loop) : 78 max(): 78
Smallest (loop): -3 min(): -3
✓ Printed by running this program, not typed by hand.
Result
In [45, 12, 78, -3, 56, 30] the largest number was 78 and the smallest -3; the loop and the built-in functions agreed.
Viva voce: what the examiner may ask
01What does append() do?
It adds one element at the end of the list.
02Why not start with largest = 0?
If all numbers were negative, 0 would wrongly stay the largest.
03What does len(nums) give?
The number of elements in the list.
Variations for the lab test
- Display the position of the largest number using
index(). - Find the sum and average of the list.
- Count how many numbers are negative.
! Common mistake Calling
nums.append(a, b) with two values raises TypeError: append() takes exactly one argument.