Mini Post: List Comprehensions As Instructions
How list comprehensions improve code readability
1 min readJul 27, 2017
Python comes with one of the most useful features of any programming language; List comprehensions.
[x**x for x in xrange(1, 10) if x % 2 == 0]
List comprehensions are useful tools for defining operations on a list. They’re easy to read and compact three essential steps into one line:
- Element manipulation —
x**x
- Iteration —
for x in xrange(1,10)
- Filtering —
if x % 2 == 0
Where list comprehensions really shine through is being used as logical steps in a sequence of operations — AKA, instructions. A really silly comparison of how this works can be seen below:
Although a trivial example this illustrates how list comprehensions allow you to define logical steps with the same high clarity in half the space.