Python

Program to find second largest number among a List in Python1 min read

Here is an example of how to find the second largest number in a list in Python:

Output:




Here is an explanation of the code step by step:

  1. The function second_largest takes a list numbers as input.
  2. Initialize two variables first and second to float('-inf'), which is a special value that represents negative infinity.
  3. Use a for loop to iterate over each number in the list numbers.
  4. In each iteration, compare the current number n with first.
    • If n is greater than first, assign first to second and n to first.
    • If n is not greater than first but is greater than second, assign n to second.
  5. After the loop, return second as the result.
  6. Initialize a list numbers with 10 values.
  7. Call the second_largest function with numbers as input and assign the result to result.
  8. Print the result using the statement print("The second largest number in the list is:", result).

This code will output: The second largest number in the list is: 9.

Leave a Comment