Python Program to Find the Second Largest Number in a List
In this tutorial, we will discuss a Python program to find the second largest number in a list.
Related: Python program to remove duplicates from a list
Program code to find the second largest number in a list in Python
# Find the Second Largest Number in a List in Python def find_second_largest(lst): lst = list(set(lst)) # Remove duplicates lst.sort() return lst[-2] if len(lst) > 1 else None input_list = [3, 5, 1, 4, 5, 2] second_largest = find_second_largest(input_list) if second_largest is not None: print(f"The second largest number is {second_largest}.") else: print("The list does not have enough unique elements.")
Explanation
- Function Definition: The
find_second_largest
function takes a list as input, removes duplicates, sorts the list, and returns the second largest number. - Main Program: The program defines a list and finds the second largest number using the
find_second_largest
function. It then prints the result.
Output
- When you run the above program, it will find the second largest number in the list and print the result.
Conclusion
- In this tutorial, we learned how to find the second largest number in a list using a Python program.
- Understanding this concept is essential for data analysis and enhancing your programming skills.