123

do you know if Python supports some keyword or expression like in C++ to return values based on if condition, all in the same line (The C++ if expressed with the question mark ?)

// C++
value = ( a > 10 ? b : c )
1
  • 5
    That C++ operator is called the "conditional operator" or the "ternary operator". Commented Feb 3, 2010 at 12:47

2 Answers 2

207
value = b if a > 10 else c

For Python 2.4 and lower you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:

value = [c, b][a > 10]

There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.

Sign up to request clarification or add additional context in comments.

5 Comments

I've always wondered what notation they rejected as "too confusing" in favour of this.
+1, You can use this kind of 'if' even with lambda expressions!
@Neil, not sure if you're referring to the syntax ultimately chosen, or who said "too confusing", but the PEP summarizes all the rejected alternatives among other info: python.org/dev/peps/pep-0308
They should have used test ? a : b. The reasons cited for its rejection are weak.
+! for Not sharing with us the 'not recomended' way ;)
2

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

1 Comment

Sadly this block form if a then b else c and the functional immediate form b if a else c are brain bendingly inverted relative to each other (Python's inverted if is backwards from nearly every other programming language's immediate if 😭).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.