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 listnumbers
as input. - Initialize two variables
first
andsecond
tofloat('-inf')
, which is a special value that represents negative infinity. - Use a
for
loop to iterate over each number in the listnumbers
. - In each iteration, compare the current number
n
withfirst
.- If
n
is greater thanfirst
, assignfirst
tosecond
andn
tofirst
. - If
n
is not greater thanfirst
but is greater thansecond
, assignn
tosecond
.
- If
- After the loop, return
second
as the result. - Initialize a list
numbers
with 10 values. - Call the
second_largest
function withnumbers
as input and assign the result toresult
. - 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
.