1. Introduction
In this tutorial, we will show you how to write a Python program to find the second largest number in a list.
The second largest number is the number that is less than the maximum but greater than all other numbers in the list. Finding this number can be done by sorting the list or iterating through it while keeping track of the two largest numbers encountered.
2. Program Steps
1. Create a list of numbers.
2. Sort the list in descending order and identify the second element, or iterate through the list to find the largest and second largest numbers.
3. Print the second largest number.
3. Code Program
# Create a list of numbers
numbers = [10, 20, 4, 45, 99, 19, 40]
# Sort the list in descending order and pick the second element
sorted_numbers = sorted(numbers, reverse=True)
second_largest = sorted_numbers[1]
# Print the second largest number
print(f"The second largest number by sorting is: {second_largest}")
# Alternatively, find the second largest number without sorting
largest = second = float('-inf')
for number in numbers:
# Update the largest and second largest accordingly
if number > largest:
second = largest
largest = number
elif number > second and number != largest:
second = number
# Print the second largest number found without sorting
print(f"The second largest number found without sorting is: {second}")
Output:
The second largest number by sorting is: 45 The second largest number found without sorting is: 45
Explanation:
1. numbers is the list of integers provided for analysis.
2. sorted_numbers is numbers sorted in descending order using sorted(numbers, reverse=True). second_largest is then set to the second element of sorted_numbers.
3. The first print statement outputs second_largest as the second largest number, obtained by sorting.
4. In the alternative approach, largest and second are initialized as negative infinity, float('-inf'), which acts as a lower bound for comparison.
5. A for loop iterates over each number in numbers. Inside the loop, largest and second are updated based on the current number.
6. The second print statement outputs second as the second largest number found without sorting the list.
7. Both methods confirm the second largest number in the list numbers is 45.
Comments
Post a Comment
Leave Comment