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 >
Yes, except that code relies on a small quirk (that raises an exception in Python 3): the fact that None
compares as smaller than a number.
Another value that works is float("-inf")
, which is a number that is smaller than any other number.
If you use that instead of None
, and just change -inf
to +inf
and >
to <
, there's no reason it wouldn't work.
Edit: another possibility would be to simply write -x
in all the comparisons on x
, e.g. do if -x <= m1:
et cetera.