ByteBoard Notes Notes

To find the third largest and third smallest number in a list

Informatics Practices XI · Experiment 09 of 36 · Python

★ CBSE suggested11-IPPython programs
Expt. No.09
Page No.18

Third largest and smallest

Aim

To write a Python program that finds the third largest and the third smallest number in a list.

Concepts used

Algorithm

  1. Input the numbers into a list (at least three).
  2. Sort the list in ascending order with sort().
  3. The third smallest is at index 2; the third largest is at index -3.
  4. Display both.

Program

# Third largest and third smallest numbers in a list nums = []n = int(input("How many numbers (at least 3)? "))for i in range(n):    nums.append(int(input("Enter a number: "))) nums.sort()print("Sorted list    :", nums)print("Third smallest :", nums[2])print("Third largest  :", nums[-3])

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python third_largest_smallest.py
How many numbers (at least 3)? 7 Enter a number: 42 Enter a number: 17 Enter a number: 88 Enter a number: 5 Enter a number: 63 Enter a number: 29 Enter a number: 71 Sorted list : [5, 17, 29, 42, 63, 71, 88] Third smallest : 29 Third largest : 63

✓ Printed by running this program, not typed by hand.

Result

After sorting, the list was [5, 17, 29, 42, 63, 71, 88]; the third smallest number was 29 and the third largest 63.

Viva voce: what the examiner may ask

01What does a negative index mean?

It counts from the end: -1 is the last element, so -3 is the third from the end.

02Does sort() return a new list?

No. It sorts the list in place and returns None.

03What would happen if two numbers were equal?

They would sit side by side after sorting and could both be counted; remove duplicates first if the question needs distinct values.

Variations for the lab test

  1. Sort in descending order with sort(reverse=True) and find the third largest at index 2.
  2. Find the second largest without sorting.
  3. Display the middle number of the sorted list.
! Common mistake Writing nums = nums.sort() sets nums to None, because sort() changes the list and returns nothing.
Back to the 11-IP index