Search code examples
pythonpython-3.xlist-comprehension

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


Solution

  • I suggest using map:

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