Reputation: 83
Can someone explain me how this syntax works in Python? How is this expression being evaluated?
b = False
a = ['123', '456'][b == True]
print(a) => 123
b = True
a = ['123', '456'][b == True]
print(a) => 456
Upvotes: 1
Views: 158
Reputation: 3
Adding to Selcuk's answer:
This is also an list indexing question. Let's make replace the values of False
and True
with its boolean equivalent 0
and 1
. We will also solve for those booleans expression in the brackets.
>>> b = 0
>>> a = ['123', '456'][0] # [b == True] is [0 == 1] is [False]
>>> print(a)
'123'
>>> b = 1
>>> a = ['123', '456'][1] # [b == True] is [1 == 1] is [True]
>>> print(a)
'456'
This looks far less intimidating. The first a
wants the value of index 0
which is 123
. The second a
wants the value of index 1
which is 456
.
You can try it out with a larger array to confirm:
>>> a = ['123','456','789'][2]
>>> a
'789'
More info on Python lists here.
Upvotes: 0
Reputation: 59315
Python booleans can implicitly be converted to integers where False
is 0
and True
is 1
. You can see it more clearly in this example:
>>> ["foo", "bar"][True]
'bar'
>>> ["foo", "bar"][False]
'foo'
Since b == True
returns a boolean its value can also be interpreted as either 0
or 1
. ['123', '456'][b == True]
simply returns the 0
th or 1
st element of the list depending on the value of b
.
That being said, this is an obfuscated and unreadable way of writing conditionals. Prefer the proper ternary expression:
a = '123' if b else '456'
Upvotes: 3