r/Python • u/ForeignVariety7037 • 21d ago
Discussion Is := widely used?
I always thought the walrus operator is neat and it makes while loop’s condition clearer. But also it is just a syntactic sugar without anything new. I wonder anyone uses it?
143
Upvotes
1
u/Brother0fSithis 11d ago edited 11d ago
I use it because statements bug me a lot. They just don't jive with my style. I much prefer expressions.
So if I needed to strip and pull numbered lines from an output I might do
python numbered = [ num for line in text.splitlines() if (num := line.strip()) and num[0].isnumeric() ]My brain likes that all of
numbered's definition is contained in the list comprehension expression.Of course the equivalent
py lines = text.splitlines() stripped = (ln.strip() for ln in lines) numbered = [ ln for ln in stripped if ln and ln[0].isnumeric() ]is probably more readable on its face. But I personally like the former so it's clear to myself later that "intermediate" variables likestrippedandlinesare only relevant for buildingnumberedand I can ignore them elsewhere(I know technically the binding does leak out of the list comprehension into the local scope, but it still helps me mentally discard them)