Adventures in Python

Adventures in Python #2

Two Paths to Comprehension?

storm_comingWhen I first learned about python’s list comprehensions I remember reading that the easiest way to think about them is as a rolled up for loop. But there’s a weird inconsistency in that approach depending on what you’re trying to achieve.

A list comprehension has one syntax if you have a single if clause conditional and a completely different syntax if you also want an else clause:

import numpy as np

obs = [13.4, 45.3, -.9, 0.001, 12.83]

# filter for observations under 20.0
under_20 = np.array([x for x in observations if x <= 20.0])

# filter for observations under 20.0 adjusting if not
clamped = np.array([x if x <= 20.0 else 20.0 - abs(x) for x in observations])

So the if clause goes at theĀ end if there’s no else clause else at theĀ start if there is.

There’s quite a lot of confusion on this syntax which is why there’s so many questions on Stack Overflow about it.

If I’m wrong, I’m happy to be told the “right” way – the “pythonic” way. But from where I stand right now this is a pointless hurdle to trip over.

Leave a Reply