I found this code on this site to find the second largest number:
def second_largest(numbers):
m1, m2 = None, None
for x in numbers:
if x >
Here we want to keep an invariant while we scan the list of numbers, for every sublist it must be
m1<=m2<={all other elements}
the minimum length of a list for which the question (2nd smallest) is sensible is 2, so we establish the invariant examining the first and the second element of the list (no need for magic numbers), next we iterate on all the remaining numbers, maintaining our invariant.
def second_smaller(numbers):
# if len(numbers)<2: return None or otherwise raise an exception
m1, m2 = numbers[:2]
if m2
Addendum
BTW, the same reasoning should be applied to the second_largest function mentioned by the OP