ByteBoard Notes Notes

Find the largest and smallest number in a list and in a tuple

Computer Science XI · Experiment 18 of 27 · Python

★ CBSE suggested11-CSPython programs
Expt. No.18
Page No.36

Largest and smallest in a list and tuple

Aim

To write a Python program that finds the largest and smallest numbers in a list (with a loop) and in a tuple (with built-in functions).

Concepts used

Algorithm

  1. Input how many numbers, then input them into a list with append().
  2. Take the first element as both largest and smallest.
  3. Compare every element and update largest and smallest.
  4. Convert the list to a tuple and find the largest and smallest with max() and min().
  5. Display both results.

Program

# Largest and smallest number in a list and in a tuple 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   :", largest, "  Smallest:", smallest) t = tuple(nums)print("Tuple     :", t)print("max(t)    :", max(t), "  min(t)  :", min(t))

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

Output

$ python largest_smallest_list_tuple.py
How many numbers? 5 Enter a number: 34 Enter a number: 12 Enter a number: 89 Enter a number: 5 Enter a number: 47 List : [34, 12, 89, 5, 47] Largest : 89 Smallest: 5 Tuple : (34, 12, 89, 5, 47) max(t) : 89 min(t) : 5

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

Result

For 34, 12, 89, 5 and 47 the loop found 89 as the largest and 5 as the smallest, and max() and min() on the tuple gave the same answer.

Viva voce: what the examiner may ask

01Why is nums[0] used as the starting value?

It is a real value from the list, so the answer is right even when all numbers are negative.

02What is the difference between a list and a tuple?

A list is mutable (it can be changed); a tuple is immutable.

03What does tuple(nums) do?

It creates a new tuple with the same elements as the list.

Variations for the lab test

  1. Also display the positions of the largest and smallest numbers.
  2. Find the second largest number.
  3. Find the largest number without changing the list, using sorted().
! Common mistake Calling max() on an empty list raises ValueError; check that n is at least 1.
Back to the 11-CS index