Skip to content
Advertisement

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

Advertisement

Answer

I suggest using map:

[ x for x in map(str.strip, f.readlines()) if x ]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement