Python Finding Second Largest Number
Syntax
num_list = [2, 5, 3, 7, 13, 1, 6]
largest_num = max(num_list)
second_largest = None
for num in num_list:
if num != largest_num:
if second_largest is None:
second_largest = num
elif num > second_largest:
second_largest = num
Example
num_list = [2, 5, 3, 7, 13, 1, 6]
largest_num = max(num_list)
second_largest = None
for num in num_list:
if num != largest_num:
if second_largest is None:
second_largest = num
elif num > second_largest:
second_largest = num
print("The second largest number in the list is:", second_largest)
Output
The second largest number in the list is: 7
Explanation
This program finds the second largest number in a list of numbers using a for loop and conditional statements.
First, the program finds the largest number in the list using the max()
function. It then initializes a variable second_largest
to None
.
Then, the program loops through each number in the list. If the number is not equal to the largest number in the list, the program checks if second_largest
is None
. If it is, the program sets second_largest
to the current number. If it is not None
, the program checks if the current number is greater than second_largest
and updates second_largest
if it is.
Finally, the program prints out the second largest number.
Use
This program is useful when you need to find the second largest number in a list of numbers in Python.
Important Points
- The
max()
function is used to find the largest number in the list. - The program initializes
second_largest
toNone
to handle edge cases where the largest number appears more than once. - The program checks if
second_largest
isNone
before updating it.
Summary
This program demonstrates how to find the second largest number in a list of numbers in Python using a for loop and conditional statements. It uses the max()
function to find the largest number, initializes second_largest
to None
, and then loops through the list to find the second largest number.