ByteBoard Notes Notes

To find the largest and smallest numbers in a list

Informatics Practices XI · Experiment 08 of 36 · Python

★ CBSE suggested11-IPPython programs
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

  1. Input how many numbers and append each to a list.
  2. Take the first element as both largest and smallest; compare every element to update them.
  3. 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

  1. Display the position of the largest number using index().
  2. Find the sum and average of the list.
  3. Count how many numbers are negative.
! Common mistake Calling nums.append(a, b) with two values raises TypeError: append() takes exactly one argument.
Back to the 11-IP index