FunkyBob,
@FunkyBob@chaos.social avatar

Today in my code I used:

result = [
term
for item in sequence
if (term := item.do_something()) != None
]

I found it less ugly than the alternative:

result = list(filter(None, [item.do_something() for item in sequence]))

Though I'm not entirely convinced it's easier to reason about.

treyhunner,
@treyhunner@mastodon.social avatar

@FunkyBob I'm always torn between using a walrus in this case or using a generator expression followed by a list comprehension. I do both, and sometimes one seems more readable than the other and sometimes the other seems more readable. 🤷

initial_results = (
term
for item in sequence
term := item.do_something()
)
result = [
term
for item in initial_results
if term != None
]

  • All
  • Subscribed
  • Moderated
  • Favorites
  • python
  • ngwrru68w68
  • rosin
  • GTA5RPClips
  • osvaldo12
  • love
  • Youngstown
  • slotface
  • khanakhh
  • everett
  • kavyap
  • mdbf
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • anitta
  • InstantRegret
  • normalnudes
  • tacticalgear
  • cubers
  • ethstaker
  • modclub
  • cisconetworking
  • Durango
  • provamag3
  • tester
  • Leos
  • megavids
  • JUstTest
  • All magazines