2

People hate on Python a lot. I just used the Python ternary operator for the first time. I found it easier to read than the C++ ternary operator:

0 if i==0 else 2 if i==segmentMax-1 else 1
vs
i==0 ? 0 : i==segmentMax-1 ? 2 : 1

I think Python did a good job in this case.

Comments
  • 10
    Please, don't. One ternary is fine, but combining them is horrible.
  • 0
    @iiii Too late. It is for a list comphrehension. It actually reads well.
  • 2
    Weirdly enough, as someone who actually really likes Python I hate its ternary, it's just an irritatingly inconsistent bit of syntax to conform to English.
  • 2
  • 22
    Always, always, always use parentheses around your ternaries.

    If you don’t, I will find you and I will stab you with your own keyboard.
  • 0
    @Root Well it feeds into an array of strings. So its surrounded by [ ]
  • 3
    @Demolishun (a == b ? 1 : (c == d ? 2 : (e … ))
  • 1
    @Root I dont generally use nested ternary in C++. I only used it in Python because I was doing it inside a comprehension which has limited capability for code blocks.
  • 1
    Elvis operator FTW! That's also why you don't chain it. Rock'n'roll is not meant to be chained.
  • 1
    @Demolishun it does not. Both of those.
  • 1
    Both are horrible to read.
  • 2
    Nested ternaries and no brackets, do you want to be shot in the back, hung by the neck while I run barb wire over your back?

    I don't care who you are, I'd print it out and slap you with it till you fixed it.

    A single if/else ternary I can live with, but the moment it's anything more complex than that, it's not for a ternary to decide anymore.
  • 1
    Nested ternaries with no parentheses will fuck you up in c# thanks to ternary having same precedent as some other operators
  • 4
    Found this gem at work the other day
  • 1
    @wackOverflow that hurts me
  • 0
    @Root Parenthesis make the Python version more readable. Thanks.
  • 0
    Python does things for the sake of being "oh Im a different language compared to others, we do things the Python way and it's cool". When in fact it's not.
  • 1
    Python has done many things right, unlike some languages *eyes js and php*
Add Comment