Skip to content
CodeItRaw
Arrays

Lesson 4/6

One pass does not have to carry a single value. To find the second largest you hold two variables: the largest and the one after it.

best = second = float("-inf")
for v in values:
if v > best:
best, second = v, best
elif v > second:
second = v
return second
When a new leader arrives the old leader does not vanish; it steps down to second. a, b = x, y changes two variables at once; the right side is worked out with the values from before the assignment.

float("-inf") is a starting value smaller than every number. It helps where you cannot start from the list's first element (two variables, one first element).

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.Go to the current lesson

  1. 01

    Runner-up

    Function

  2. 02

    Second Largest

    Code reading · Break the Code

  3. 03

    Odd Squares

    Code reading · Predict the Output

If you would rather not wait for the order, every problem is open without locks: Problem list