Python: Find Second Largest in List

1. Introduction

Finding the second largest number in a list is a common problem in programming and data analysis. Python offers a variety of ways to solve this problem. In this guide, we'll explore a simple method using Python's built-in sorting function.

2. Program Overview

The program will:

1. Define a list with several integer elements.

2. Use Python's built-in sorted function to sort the list.

3. Extract the second last element from the sorted list, which will be the second largest number.

4. Display the result.

3. Code Program

# Define a list with several integer elements
num_list = [34, 78, 12, 67, 89, 90, 64, 21]

# Sort the list
sorted_list = sorted(num_list)

# Get the second last element from the sorted list
second_largest = sorted_list[-2]

# Display the result
print("List of numbers:", num_list)
print("Second largest number:", second_largest)

Output:

List of numbers: [34, 78, 12, 67, 89, 90, 64, 21]
Second largest number: 89

4. Step By Step Explanation

1. We first define a list named num_list containing a series of numbers.

2. To find the second largest number, we employ Python's built-in sorted() function. The sorted() function returns a new list containing all items from the original list in ascending order.

3. After sorting, the last element in the list is the largest number, and the second last element becomes the second largest. We extract this using the indexing notation sorted_list[-2].

4. Finally, we print the original list and the second largest number for verification.

Note: There are other methods to find the second largest number without sorting the list, but using sorted() provides an easy-to-understand approach for beginners. However, for larger datasets, sorting might not be the most efficient method, and other approaches like iterating through the list might be more appropriate.

Comments