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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#code4example.com def second_largest(numbers): first = second = float('-inf') for n in numbers: if n > first: second = first first = n elif first > n > second: second = n return second numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = second_largest(numbers) print("The second largest number in the list is:", result) |

Output:

1 2 3 |
The second largest number in the list is: 9 |

Here is an explanation of the code step by step:

- The function
`second_largest`

takes a list`numbers`

as input. - Initialize two variables
`first`

and`second`

to`float('-inf')`

, which is a special value that represents negative infinity. - Use a
`for`

loop to iterate over each number in the list`numbers`

. - 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`

.

- If
- After the loop, return
`second`

as the result. - Initialize a list
`numbers`

with 10 values. - Call the
`second_largest`

function with`numbers`

as input and assign the result to`result`

. - 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`

.

## Add comment