Skip to content

Write a Python program to find the second largest number in a list | Code

  • by

Use the sort() method and negative indexes to write a Python program to find the second largest number in a list.

Python program to find the second-largest number in a list

Simple example code printing the second last element. Simply just sort the given list in ascending order and get the second last element in the list.

list1 = [10, 20, 70, 40, 90]

# sorting the list
list1.sort()

print("Second largest element is:", list1[-2])

Output:

Write a Python program to find the second largest number in a list

Another way Removing the maximum element

Use the set() function, max() & remove() function.

list1 = [10, 20, 70, 40, 90]

new_list = set(list1)
# removing the largest element from list1
new_list.remove(max(new_list))

print(max(new_list))

Output: 70

Here’s Another Python program to do that:

def second_largest(numbers):
    # Check if the list has at least two elements
    if len(numbers) < 2:
        return "List should have at least two numbers."

    # Sort the list in descending order
    numbers.sort(reverse=True)

    # The second largest number is the second element in the sorted list
    return numbers[1]

# Example usage:
my_list = [10, 5, 8, 20, 2]
result = second_largest(my_list)

if type(result) == int:
    print("The second largest number in the list is:", result)
else:
    print(result)

In this program, we define a function called second_largest that takes a list of numbers as its argument. It first checks if the list has at least two elements to ensure there’s a second largest number. Then, it sorts the list in descending order using the sort method with the reverse=True argument. Finally, it returns the second element of the sorted list, which is the second largest number.

The example usage at the end of the program demonstrates how to use the second_largest function with a sample list. You can replace my_list with your own list of numbers to find the second largest number in your data.

Comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading