Mini Post: List Comprehensions As Instructions

How list comprehensions improve code readability

Adam Short
Jul 27, 2017 · 1 min read
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.

Adam Short

Written by

full stack engineer 🐺 18. works @ Stella AI

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade