Python Program to Find the Second Largest Number in a List (3 Methods)

By Btech Faqa

Published On:

Join WhatsApp

Join Now

A Python program to find the second largest number in a list identifies the second-highest distinct numerical value from a collection of numbers. You can solve this problem using Python’s sort() method, the built-in sorted() function, or a loop that tracks the largest and second-largest values.

For example, if the input list is [10, 25, 8, 40, 30], the largest number is 40, and the second largest number is 30.

numbers = [10, 25, 8, 40, 30]

unique_numbers = sorted(set(numbers))

if len(unique_numbers) >= 2:
    print("Second largest number:", unique_numbers[-2])
else:
    print("A second distinct largest number does not exist")

Output:

Second largest number: 30

This tutorial explains three different methods, provides complete Python programs with output, discusses duplicate values and edge cases, and answers common questions asked by beginners.

What Is the Second Largest Number in Python?

The second largest number is the second-highest distinct value in a list of numbers.

Consider this example:

numbers = [12, 45, 23, 67, 34]

The numbers in descending order are:

67, 45, 34, 23, 12

Therefore:

  • Largest number: 67
  • Second largest number: 45
  • Third largest number: 34

The goal is to write a Python program that finds the value 45 without manually checking every number.

This problem is common in Python programming exercises, coding interviews, introductory data-processing tasks, and computer science laboratory practice.

Why is this problem important?

Finding the second largest number helps you understand several fundamental Python concepts:

  • Lists and numerical data.
  • Sorting and comparison operations.
  • Loops and conditional statements.
  • Sets and duplicate removal.
  • Variables and value tracking.
  • Time and space complexity.
  • Handling empty lists and invalid inputs.

Once you understand this example, you can apply similar techniques to find the second smallest number, the third largest number, or the highest values in a dataset.

Method 1: How Do You Find the Second Largest Number Using sort()?

Python lists provide a built-in sort() method that arranges list elements in ascending or descending order.

The following program sorts the list in ascending order and retrieves the second-highest distinct number.

Python program

numbers = [10, 25, 8, 40, 30]

numbers.sort()

unique_numbers = list(set(numbers))

unique_numbers.sort()

if len(unique_numbers) >= 2:
    print("Second largest number:", unique_numbers[-2])
else:
    print("No second distinct largest number exists")

Output

Second largest number: 30

Explanation

  1. The list contains five numbers: 10, 25, 8, 40, and 30.
  2. The sort() method arranges the original list in ascending order.
  3. The set() function removes duplicate values if any exist.
  4. list() converts the set back into a list.
  5. The second sort() arranges the distinct values in ascending order.
  6. The expression unique_numbers[-2] retrieves the second-to-last element.

The second-to-last element is the second largest because the list is sorted from smallest to largest.

Important: A shorter version can use sorted(set(numbers)), which combines sorting and duplicate removal into one expression.

Method 2: How Do You Find the Second Largest Number Using sorted()?

The sorted() function returns a new sorted list instead of modifying the original list.

This is useful when you want to preserve the original order of the input list.

Python program

numbers = [15, 50, 25, 80, 60]

sorted_numbers = sorted(set(numbers))

if len(sorted_numbers) >= 2:
    second_largest = sorted_numbers[-2]
    print("Second largest number:", second_largest)
else:
    print("No second distinct largest number exists")

Output

Second largest number: 60

Explanation

The sorted() function arranges the distinct values in ascending order.

The list becomes:

[15, 25, 50, 60, 80]

Python supports negative indexing, so:

  • sorted_numbers[-1] returns 80, the largest number.
  • sorted_numbers[-2] returns 60, the second largest number.
  • sorted_numbers[-3] returns 50, the third largest number.

The condition len(sorted_numbers) >= 2 ensures that at least two distinct values exist before accessing the second-largest element.

What is the advantage of using sorted()?

The original list remains unchanged.

For example:

numbers = [30, 10, 50, 20]

sorted_numbers = sorted(numbers)

print("Original list:", numbers)
print("Sorted list:", sorted_numbers)

Output:

Original list: [30, 10, 50, 20]
Sorted list: [10, 20, 30, 50]

Use sorted() when you need a sorted copy of a list.

Method 3: How Do You Find the Second Largest Number Using a Loop?

A loop-based solution finds the second largest number without sorting the entire list.

This method is especially useful for learning algorithms and understanding how comparisons work.

Python program

numbers = [10, 25, 8, 40, 30]

largest = None
second_largest = None

for number in numbers:
    if largest is None or number > largest:
        second_largest = largest
        largest = number
    elif number != largest and (
        second_largest is None or number > second_largest
    ):
        second_largest = number

if second_largest is None:
    print("No second distinct largest number exists")
else:
    print("Second largest number:", second_largest)

Output

Second largest number: 30

How does the loop work?

The program uses two variables:

  • largest stores the largest value found so far.
  • second_largest stores the second-largest distinct value found so far.

Initially, both variables are None, indicating that no numbers have been processed.

When the loop encounters a number larger than largest, it moves the previous largest value into second_largest and updates largest.

Otherwise, if the number is smaller than largest but larger than the current second_largest, the program updates second_largest.

The condition number != largest prevents duplicate copies of the largest value from being treated as the second largest.

Example walkthrough

Consider this list:

numbers = [10, 25, 8, 40, 30]
Number processedLargest so farSecond largest
1010Not found
252510
82510
404025
304030

The final answer is 30.

This approach takes linear time, making it more efficient than sorting when you only need the two largest distinct values.

Which Method Is Best for Finding the Second Largest Number?

Different approaches are useful in different situations.

MethodTime complexityExtra spaceMain advantage
sort() with distinct valuesTypically O(n log n)O(n) or moreEasy to understand
sorted(set(numbers))Typically O(n log n)O(n)Concise and readable
Single loopO(n)O(1)Efficient for finding two distinct maximum values

Here, n represents the number of elements in the input list. Complexity figures are typical for Python’s built-in sorting and set operations.

Recommendation: Beginners can start with sorted(set(numbers)). If you want to understand algorithms or prepare for coding interviews, learn the loop-based method as well.

How Do You Handle Duplicate Numbers in a Python List?

Duplicate values are an important consideration when finding the second largest number.

For example:

numbers = [10, 40, 40, 30, 20]

The largest value is 40, and the second largest distinct value is 30.

The number 40 appears twice, but it should not be counted as the second largest distinct value.

Use set() to remove duplicates before sorting:

numbers = [10, 40, 40, 30, 20]

unique_numbers = sorted(set(numbers))

if len(unique_numbers) >= 2:
    print("Second largest number:", unique_numbers[-2])
else:
    print("No second distinct largest number exists")

Output:

Second largest number: 30

What happens if all numbers are the same?

Consider:

numbers = [20, 20, 20, 20]

After duplicate removal, the list contains only one distinct value:

[20]

There is no second distinct largest number.

The correct result is therefore a message explaining that a second distinct value does not exist.

This is why it is important to check the number of distinct values before accessing the second-to-last element.

How Do You Find the Second Largest Number Without Using sort()?

If you are not allowed to use sort() or sorted(), you can solve the problem with a single loop.

numbers = [5, 12, 9, 25, 18]

largest = None
second_largest = None

for number in numbers:
    if largest is None or number > largest:
        second_largest = largest
        largest = number
    elif number < largest and (
        second_largest is None or number > second_largest
    ):
        second_largest = number

if second_largest is None:
    print("No second distinct largest number exists")
else:
    print("Second largest number:", second_largest)

Output:

Second largest number: 18

This version uses comparisons and variable updates rather than sorting.

It is useful for coding exercises that specifically prohibit sorting functions.

The loop examines each element once, so its time complexity is O(n), and it uses O(1) extra space for the two tracking variables.

How Do You Find the Second Largest Number in a List of Negative Numbers?

Python comparisons work with negative numbers in the same way they work with positive numbers.

For example:

numbers = [-10, -5, -20, -2, -8]

unique_numbers = sorted(set(numbers))

if len(unique_numbers) >= 2:
    print("Second largest number:", unique_numbers[-2])
else:
    print("No second distinct largest number exists")

Output:

Second largest number: -5

The largest number is -2, and the second largest is -5.

Remember that a negative number closer to zero is greater than a negative number farther from zero.

For example, -2 > -5 is true.

How Do You Handle an Empty List?

An empty list contains no values, so it cannot have a largest or second largest number.

Example:

numbers = []

unique_numbers = sorted(set(numbers))

if len(unique_numbers) >= 2:
    print("Second largest number:", unique_numbers[-2])
else:
    print("A second distinct largest number does not exist")

Output:

A second distinct largest number does not exist

This example handles an empty list without raising an IndexError.

In real applications, you may want to provide a more specific message for an empty list and a separate message when a list contains only one distinct value.

How Do You Find the Second Largest Number in a List of User Inputs?

You can also ask users to enter numbers from the keyboard.

The following program accepts space-separated integers.

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

unique_numbers = sorted(set(numbers))

if len(unique_numbers) >= 2:
    print("Second largest number:", unique_numbers[-2])
else:
    print("Enter at least two distinct numbers")

Example input:

Enter numbers separated by spaces: 12 45 23 67 34

Output:

Second largest number: 45

The input() function reads the entered text. The split() method separates the values, map(int, ...) converts them into integers, and list() creates the Python list.

This program assumes that the user enters valid integers. If the input contains letters or invalid values, Python raises a ValueError. A production-ready program should catch that exception and request valid input again.

Common Mistakes When Finding the Second Largest Number

Beginners often make several mistakes when writing this program.

1. Forgetting to remove duplicates

If the list is [10, 40, 40, 30], using a sorted list without removing duplicates can return 40 as the second-to-last value.

If the requirement is the second largest distinct number, use set() or explicitly skip duplicate values.

2. Using the wrong index

In ascending order, numbers[-1] is the largest element, while numbers[-2] is the second-to-last element.

However, negative indexing is only safe when the list contains enough elements.

3. Not checking list length

If the list contains fewer than two distinct numbers, the second largest distinct number does not exist.

Always validate the number of distinct values before accessing the required index.

4. Assuming the list contains only positive numbers

Negative numbers and zero are valid numerical values. A correct program should compare values rather than assume every number is positive.

5. Modifying the original list unintentionally

The sort() method modifies a list in place. If you want to preserve the original list, use sorted() instead.

6. Confusing the second element with the second largest

The second element in an unsorted list is not necessarily the second largest. The list must be sorted or examined using a suitable comparison algorithm.

Practice Questions for Python Beginners

Try solving the following exercises to strengthen your understanding.

  1. Write a Python program to find the largest number in a list.
  2. Write a program to find the second smallest distinct number.
  3. Find the third largest distinct number in a list.
  4. Find the second largest number without using sorting functions.
  5. Write a program that handles an empty list.
  6. Find the second largest number when the list contains duplicate values.
  7. Find the second largest value in a list containing negative numbers.
  8. Modify the user-input program to handle invalid input.
  9. Compare the execution time of the sorting method and the loop method on a large list.
  10. Write a function that returns the second largest distinct number instead of printing it.

These exercises help you practise loops, conditional statements, list operations, functions, and algorithmic thinking.

Frequently Asked Questions

1. How do you find the second largest number in Python?

Use sorted(set(numbers)) to sort the distinct values, then access [-2] if at least two distinct values exist.

2. What is the easiest way to find the second largest number?

The easiest readable method for beginners is sorted(set(numbers))[-2], with a length check to handle lists that do not contain two distinct values.

3. Can I find the second largest number without sorting?

Yes. Use a loop that tracks the largest and second-largest distinct values. This takes O(n) time and O(1) extra space.

4. What is the difference between sort() and sorted()?

sort() modifies the original list and returns None. sorted() returns a new sorted list and leaves the original list unchanged.

5. How do I find the second largest number when duplicates exist?

Remove duplicates using set() before sorting, or use a loop that skips values equal to the largest number.

6. What happens if a list has only one distinct number?

A second largest distinct number does not exist. The program should display a suitable message or return a value such as None.

7. Can the second largest number be negative?

Yes. For example, in [-10, -5, -20, -2], the second largest distinct number is -5.

8. What is the time complexity of finding the second largest number?

Sorting generally takes O(n log n) time. A single-pass loop can find the two largest distinct values in O(n) time.

9. Is this program useful for coding interviews?

Yes. It tests list manipulation, comparisons, loops, duplicate handling, edge cases, and time complexity.

10. Can I use this method with floating-point numbers?

Yes, provided the list contains comparable numeric values. For example, [2.5, 7.8, 4.1] has 4.1 as its second largest distinct value.

Conclusion

A Python program to find the second largest number in a list is a useful exercise for beginners who want to learn list operations, sorting, loops, and conditional statements.

The simplest general approach is to remove duplicates, sort the remaining values, and retrieve the second-to-last element after checking that at least two distinct values exist.

For example:

numbers = [10, 25, 8, 40, 30]

values = sorted(set(numbers))

if len(values) >= 2:
    print(values[-2])
else:
    print("No second distinct largest number exists")

Output:

30

If you want to improve your algorithm skills, practise the single-loop approach as well. It finds the second largest distinct value in linear time without sorting the entire list.

🔴Related Post

Leave a Comment