Write a Python program that reads a list of integers from the user and finds…

2025

Write a Python program that reads a list of integers from the user and finds the second largest unique number. Assume the list has at least two unique values.

(a) Provide the complete Python code to solve the problem.

(b) If the user enters the numbers: 5, 3, 9, 1, 5, 3, 8, what will be the output?

(c) Briefly explain how your code ensures the correct result even when there are duplicate values in the list.

Show answer & explanation

(a) Python program

The following Python program reads a list of integers from the user, removes duplicate values, and finds the second largest unique number.

nums = input("Enter numbers separated by spaces: ")
numbers = list(map(int, nums.split()))

unique_numbers = list(set(numbers))

unique_numbers.sort(reverse=True)

second_largest = unique_numbers[1]

print("Second largest unique number:", second_largest)

(b) Output for given input

If the user enters the numbers:

5 3 9 1 5 3 8

First the program converts the list into unique values:

{1, 3, 5, 8, 9}

After sorting in descending order:

[9, 8, 5, 3, 1]

The second largest number is:

Second largest unique number: 8

(c) Explanation

The program first reads the input numbers and converts them into a list of integers. To handle duplicate values, the list is converted into a set using the set() function. A set automatically removes duplicate elements and keeps only unique numbers.

After removing duplicates, the unique numbers are converted back to a list and sorted in descending order. The element at index 1 represents the second largest value in the list. This ensures that even if the user enters repeated numbers, the program correctly identifies the second largest unique number.

Explore the full course: Hpsc Pgt Computer Science