4 ms·
I generally like python's list comprehensions, but they have some ugly warts. For example, a simple comprehension looks like this: foo = [transform(bar) for
by zimzam 10y ago
I generally like python's list comprehensions, but they have some ugly warts. For example, a simple comprehension looks like this:
foo = [transform(bar) for bar in baz.list()]
Adding an if condition looks like this:
foo = [transform(bar) for bar in baz.list() if condition(bar)]
But an if/else expression looks like this:
foo = [if condition(bar) transform(bar) else other_transform(bar) for bar in baz.list()]
Adding an else requires completely rewriting the line! Super ugly and inconsistent.
Edit: formatting... don't know why my the 'list()' in my last example is disappearing
- marcstreeter 10y agomaybe it's bad form but I generally prefer to break my list/dictionary/set comprehensions into various lines. For me it increases the readability foo = [ if condition(bar) transform(bar) else other_transform(bar) # 1: storage for bar in base.list() # 2: iteration if bar_tester(bar). # 3: filtering ] to each his own I suppose, until the PEP8 police come and get us all!!!
- dragonwriter 10y agoFilters and ternaries aren't the same kind of thing (ternary if/else are analogous to SQL SELECT-clause case statements, filter if is analogous to SQL WHERE-clause; the positions in Python conditionals, which are very much like SQL SELECT statements, follows that analogy.)