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

Time:08-19

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).

CodePudding user response:

I suggest using map:

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

CodePudding user response:

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']

CodePudding user response:

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.

  • Related