Home / Python Tutorial / Day 10
Day 10 — Python list comprehensions
One line that replaces four. Once this clicks, your Python starts looking like a professional wrote it.
The long way first
The same thing in one line
How to read it
Read the middle first:
for n in numbers. Then the front: n * 2 — what to do with each one. So: "for every n in numbers, give me n times 2".Adding a filter
Working with text
Real data work
Turning text into numbers
Data read from a file arrives as text. This is how you convert a whole column at once.
Know when to stop
Comprehensions are for simple transforms. If you need several conditions and a couple of steps, a normal
for loop is easier for the next person to read — and that person is often you, six months later.Try these yourself
- Build a list of squares from 1 to 10.
- Filter a list of amounts to only those above 25000.
- Convert ["1","2","3"] to numbers and total them.
- Take a list of names and produce their lengths.
Ready for pandas and real projects?
This tutorial covers core Python. Our Data Analytics course takes you into pandas, NumPy, real files and visualisation, with mentor support and portfolio projects.
See the course →