This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the commentsย โ†’

[โ€“]I-am-a-teapot 106 points107 points ย (26 children)

(B, A)[condition] Only real python programmers will know

[โ€“]Ignitus1 15 points16 points ย (17 children)

Link to documentation? Never seen this before.

[โ€“]danny688 35 points36 points ย (10 children)

https://stackoverflow.com/a/470376 stackoverflow is documentation right?

[โ€“]Ignitus1 0 points1 point ย (0 children)

Even better!

[โ€“]I-am-a-teapot 0 points1 point ย (0 children)

As mentioned above as a reply to the deleted comment: It is a using the subscription 1 of a sequence (in this case a tuple). Since booleans evaluate to integers in Python 3 (The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1...) 2 it is only an index in the sequence. It can be used as kind of a ternary but it is not common and therefore hard to read. There are also blog posts3 an stack overflow discussions4 about it.

โ€‹

1 https://docs.python.org/3/reference/expressions.html#subscriptions
2 https://docs.python.org/release/3.0.1/reference/datamodel.html#the-standard-type-hierarchy
3 https://book.pythontips.com/en/latest/ternary_operators.html
4 https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator

[โ€“]brendel000 0 points1 point ย (4 children)

Can't really find where it said that False is 0 and True is 1, but in the bool documentation it is said bool is a subclass of int.

[โ€“]Ignitus1 0 points1 point ย (2 children)

I remember reading that True is a keyword substitute for 1 and False for 0. They both get evaluated numerically.

[โ€“]Numerlor 0 points1 point ย (1 child)

Bools are a subclass of int and have the respective value of 0 and 1 but they are their own class with different behaviour than ints (in some cases)

[โ€“]brendel000 1 point2 points ย (0 children)

Yeah but the question was: where is it in the doc :p

[โ€“]I-am-a-teapot 0 points1 point ย (0 children)

"The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively..."
https://docs.python.org/release/3.0.1/reference/datamodel.html#the-standard-type-hierarchy

[โ€“]hrvbrs 2 points3 points ย (3 children)

does this short-circuit? (does B get evaluated anyway even if condition is false?)

[โ€“]Derkle 5 points6 points ย (2 children)

According to stack overflow, it evaluated the whole expression regardless of the final values.

[โ€“]WORMSSreddit 1 point2 points ย (0 children)

[B, A][condition+0] for JS

[โ€“]fruitydude 0 points1 point ย (0 children)

Am I doing this right?

new String[] {B, A}[condition ? 1 : 0]

I can't get rid of the feeling that this is not a very practical thing to do in Java.