Hone

Lessons · Python · list comprehensions

Build a list in one line

[expression for item in items if condition] makes a new list from an old one: transform, filter, or both.

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

Half of data work is 'take these, keep the ones that..., turn each into...'. A comprehension says that in one readable line and runs faster than the loop it replaces.

How to think about it

Which items, and what do I want from each? Write the loop first if you need to. Then fold it: the thing you append becomes the expression at the front; the for stays; the if moves to the end.

Worked example

words = ["tea", "coffee", "milk"]
Input.
long_upper = [w.upper() for w in words if len(w) > 3]
For each w, keep it if longer than 3, and put its upper-case form in the new list.
print(long_upper)
["COFFEE", "MILK"]. tea was filtered out.

Your turn

Make a list of the squares of only the positive numbers.

nums = [-2, 3, -1, 4]
squares = [n * n for n in nums  n > 0]

The trap

Nesting two comprehensions to look clever. If it takes more than a glance to read, it is a loop that should have stayed a loop.

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