1

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

2 Answers 2

3

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 0th or 1st 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'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the explanation it's perfectly clear for me (and for the grammar correction)
0

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.

3 Comments

Correction: These are lists, not arrays. Python arrays are different.
Thanks, i understand !
Ah yes, sorry about that! Those are lists, not arrays. I even linked a Python list resource too lol. Edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.