x: max and second_last
9: 9 and 9
6: 9 and 9
4: 9 and 9
10: 10 and 9
13: 13 and 9 <<<
2: 13 and 9
3: 13 and 9
5: 13 and 9
You are essentially losing information about second_last
, which is held by max
until it is replaced by x
when x > max
. Whenever max
is updated, technically second_last
should also be updated, as the old max
is the new second_last
.
Notice that if the first if
statement is satisfied, the second cannot be satisfied, so max
and second_last
are never updated simultaneously.
So, unless there is some value y
further down in the iteration such that second_last < y != max
- Eg: list = [9, 12, 10]
, y = 10
-, your code will produce incorrect outputs. So, your code never updates second_last
when the sequence is strictly increasing.
Here is a fix for your code:
list = [9, 6, 4, 10, 13, 2, 3, 5]
max = list[0]
second_last = list[0]
for x in list:
if x > max:
second_last = max # add this line
max = x
elif x > second_last and x != max:
second_last = x
print(second_last)
Besides, it is a good idea, not to assume the list is non-empty.