Mini Post: List Comprehensions As Instructions

How list comprehensions improve code readability

Adam Marshall
1 min readJul 27, 2017
Python is ❤️

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:

  1. Element manipulation — x**x
  2. Iteration — for x in xrange(1,10)
  3. 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.

--

--