Skip to content
CodeItRaw
Arrays

Lesson 5/6

When the answer is a list and not a number, building a new one is nearly always easier and safer than trying to change the one you have.

out = []
for v in values:
if v != 0:
out.append(v)
return out + [0] * (len(values) - len(out))
Collect the non-zeros in order, then add as many zeros as there are places missing. [0] * 3 is [0, 0, 0]; + joins two lists end to end.

There is a short form: [v for v in values if v != 0]. This is a list comprehension and does the same as the loop above. Use it while it reads easily; once it holds two conditions and a calculation, go back to the loop.

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

    Zeros to the Back

    Function

  2. 02

    Sliding Window

    Code reading · Bug Hunt

  3. 03

    Ordered Pairs

    Code reading · Read the Big-O

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