4 ms·
I'm a fan of Python's conditional expressions. foo = bar if qux is None else baz They're particularly interesting when combined with comprehensions.
by rectangletangle 12y ago
I'm a fan of Python's conditional expressions.
foo = bar if qux is None else baz
They're particularly interesting when combined with comprehensions.
['a' if i % 2 == 0 else 'b' for i in range(10)]
Though this particular example can be expressed much more concisely.
['a', 'b'] * 5
- TillE 12y agoThat's a Pythonization of C's conditional operator. foo = qux == NULL ? bar : baz; Of course, C does not do list comprehensions.
- plikan13 12y agoBefore the conditional expression was introduced to Python I sometimes wrote things like foo = [baz, bar][qux is None]
- misiti3780 12y agoi didnt realize you could add the if statement in the comprehension where you did ['a' if i % 2 == 0 else 'b' for i in range(10)] very cool! I was on aware of code like ['a' for i in range(10) if i % 2 == 0]
- misiti3780 12y agoi didnt realize you could add the if statement in the comprehension where you did ['a' if i % 2 == 0 else 'b' for i in range(10)] very cool! I was only aware of code like ['a' for i in range(10) if i % 2 == 0]