i30817
i30817

Reputation: 1378

In python list comprehensions is there a way not to repeat work

I'm not sure this is needed, since the optimizer might take care of it but the question is about:

[ x.strip() for x in f.readlines() if x.strip() ]

both sides need the strip, (just 'if x' is not enough).

Upvotes: 1

Views: 58

Answers (3)

rici
rici

Reputation: 241931

While the most general solution is probably the so-called walrus operator (:=), in this particular case you're probably better off using the standard library function filter.

Here's one of many possibilities.

[*filter(None, (map(str.strip, f.readlines())))]

Specifying the predicate as None means that only truthy values are kept.

Upvotes: 1

kaya3
kaya3

Reputation: 51152

I suggest using map:

[ x for x in map(str.strip, f.readlines()) if x ]

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195593

Yes, if you use sufficiently high version of Python (3.8+) you can use assignment operator :=:

lst = [" aa ", " bb "]

out = [v for x in lst if (v := x.strip())]
print(out)

Prints:

['aa', 'bb']

Upvotes: 1

Related Questions