Hello, I've loved Python ever since I picked it up a couple years ago, but I have a question about the proper way to do something. There's a way of condensing an if/else conditional that has 2 options (True, False), for simple things.
Assume that playerWins is a boolean:

if playerWins:
    print 'You win!'
    print 'You lose...'

Now, this can also be executed just as easily by writing:

[ print 'You lose...', print 'You win!' ][ playerWins ]

Which way is the proper way? I'm assuming that the first one is due to it being slightly more readable (a nice goal of Python), but if I'm looking to condense simple things in my code like this, is it wrong to use the second way? And what about speed? Is there any difference in efficiency between these two?

I'm self-taught so I never had anyone explicitly tell me these fine details of Python, but if anyone knows the 'standard' for this sort of thing, can you let me know? Thanks!

8 Years
Discussion Span
Last Post by shadwickman

Starting with python 2.5, you can write

print("You Win!" if playerWins else "You lose!")

The syntax is value = expressionA if conditionExpression else expressionB . Note that the condition is always computed first, and only one of A an B is executed.

Votes + Comments
great explanation of the syntax!

Wow, I hadn't seen that functionality before. Thanks so much, it's definitely going to be a big help!

Just out of curiosity, what about something like:

[ print "No, it's false", doTrueFunction() ][ booleanValue ]

where the two options aren't similar. Is there any special syntax for that?


You can't use print as an expression before 3.0. In 3.0 you can write

doTrueFunction() if booleanValue else print("No, it's false")

before 3.0, you could write

doTrueFunction() if booleanValue else sys.stdout.write("No, it's false\n")

The problem with the syntax

[expressionA(), expressionB()][bool(expressionC())]

is that all 3 expressions are evaluated before the choice is made.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.