by jreese · 4y ago · 0 comments
values = [
value
for line in buffer.readlines()
if (value := line.strip())
]
Previously, I would have needed to either duplicate effort like: values = [
line.strip()
for line in buffer.readlines()
if line.strip()
]
Or used a sub-generator: values = [
value
for value in (
line.strip() for line buffer.readlines()
)
if value
]
Or rewritten it altogether using a (slower) for loop calling append each time: values = []
for line in buffer.readlines():
line = line.strip()
if line:
values.append(line)
The assignment expression is perfect for this sort of use case, and is a clear win over the alternatives IMO.Edit: fixed initial example
stripped_lines = (line.strip() for line in buffer.readlines())
non_empty_stripped_lines = [line for line in stripped_lines if stripped_lines]Breaking down things in clear steps is underrated I think.
values = [
value
for line in buffer.readlines()
for value in (line.strip(),)
if value
] nonblank = [value for line in file for value in [line.strip()] if value] open("file", "r").readlines.
map{|line| line.strip}.
filter{|line| line != ""}
or some smarter but less readable ways.I prefer the left-to-right transformations style to Python's list comprehension and inside-to-outside function composition. The reason is that it reminds me of how data flow into *nix pipelines. I spent decades working with them and I've been working with Ruby for the last half of that time. With Python in the last quarter of my career.
It's a matter of choices and preferences of the original designed of the language. Both ways work.
filter(None, xs)
is equivalent to: filter(lambda x: x, xs)
That is, it will return an iterator over the truthy elements of the passed iterable.If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
So it just removes false-y values.
Very handy I've used it a ton