Hone

Lessons · Python · build the list outside the loop

Build the list outside the loop

Create an empty list before the loop, append inside it, and use it after. One list, filled one item at a time.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Filtering matching records, gathering the lines that failed, collecting every price over a limit: half of everyday code is walk a sequence, keep some of it.

How to think about it

Three places: the empty list above the loop, the append inside, the use below. If the list is created inside the loop it starts over every time and you keep one item.

Worked example

out = []
Empty, created once, before the loop.
for x in [1, 2, 3, 4]:
Walk every item.
    if x % 2 == 0:
Keep the even ones.
        out.append(x * 10)
Add inside the loop.
print(out)
[20, 40]: both kept, in order.

Your turn

Keep every word longer than three letters.

long = []
for w in words:
    if len(w) > 3:
        long.(w)

The trap

out = out.append(x) sets out to None, because append returns nothing. Call it on its own line.

Practise build the list outside the loop on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.