Follow

In Python, you can filter a list comprehension by adding an if statement to the end, e.g.:

[x for x in list if x<y]

I wish you could do the same in a for loop, e.g.:

for x in list if x<y:
...print(x)

· · Web · 3 · 0 · 3

@christianp closest you can get is "for x in [x for x in list if x<y]" but it feels a bit silly

@chambln
The Pythonic way is to do what you wrote but substitute [ ] with ( ). Thus it becomes a generator.

for x in (x in list if x < y): ...

The functional programming way is to use a filter function.

for x in filter(lambda x: x < y, list): ...

@christianp

@olligobber what if I want to do more than one thing? What if my loop is so enormous that storing the result of each step would cause problems?

@christianp Just def do(*args): return None, then [do(a := a + 1, a := a * 2, a := a * a) for _ in range(10)] works

@christianp This is really cursed and I do not recommend actually doing it, but it works?

Sign in to participate in the conversation
Mathstodon

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!