In python list comprehensions is there a way not to repeat work
Question:
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).
Answers:
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']
I suggest using map
:
[ x for x in map(str.strip, f.readlines()) if x ]
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.
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).
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']
I suggest using map
:
[ x for x in map(str.strip, f.readlines()) if x ]
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.