Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Shorter, more pythonic way of writing an if statement

I have this

bc = 'off'
if c.page == 'blog':
 bc = 'on'
print(bc)

Is there a more pythonic (and/or shorter) way of writing this in Python?

Answer*

Draft saved
Draft discarded
Cancel
7
  • Fascinating. As with another one above, could you generalize that a bit more and explain it? (As in ... you weren't kidding about #3). Commented Aug 23, 2009 at 20:46
  • ("off", "on") is a tuple and c.page=="blog" evaluates to the index of the element that is being accessed Commented Aug 23, 2009 at 20:58
  • 3
    I wanted to vote down because it's really ugly, then I remembered that I used it myself. Commented Aug 23, 2009 at 21:16
  • 4
    This is what I use when 2.5 isn't available; I find ‘and...or’ unacceptable as it reads weirdly and fails if the and-value is something that isn't truthy. The drawback of ‘(a, b)[cond]’ is that both a and b are evaluated, so you can't rely on shortcutting, which means you can't convert a construct like "'nothing' if item is None else item.name". Commented Aug 23, 2009 at 22:20
  • 4
    I like it but compared to X if Z else Y is that if Z is false we only evaluate Y not X so it fails for example if key not in dictionary: adict[ k ] if adict.__contains( k ) else k Commented Aug 24, 2012 at 2:22

lang-py

AltStyle によって変換されたページ (->オリジナル) /