3 ms·
You can write it this way: values = [ value for line in buffer.readlines() for value in (line.strip(),) if value ]
by compressedgas 4y ago
You can write it this way:
values = [
value
for line in buffer.readlines()
for value in (line.strip(),)
if value
]
- jreese 4y agoFWIW, that version ends up being slower, because you're constructing and iterating over a tuple for every iteration, which incurs a similar cost to running `.strip()` twice. The sub-generator example I gave is better because you're only constructing the generator expression once, and requires less overhead for each iteration.
- d0mine 4y agoIt is unlikely (unless there is a benchmark that says otherwise). Before the walrus operator, the single item loop could have been used: nonblank = [value for line in file for value in [line.strip()] if value]