I don't understand this syntax.
Python program to demonstrate ternary operator
a, b = 10, 20
Use tuple for selecting an item
print( (b, a) [a < b] )
Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
PS: I guess this is from older version of Python, because in newer versions (don't know from which version) True and False are reserved keywords, so they can't be assigned a value.
lamda is more efficient than above two methods because in lambda we are assure that only one expression will be evaluated unlike in tuple and Dictionary
print((lambda: b, lambda: a)[a < b]())
Syntax should be:
[on_true] if [expression] else [on_false]
So how does
print( (b, a) [a < b] )
print({True: a, False: b} [a < b])
print((lambda: b, lambda: a)[a < b]())
fit this syntax?
What's the meaning of [a<b]
after tuple/dictionary/lambda? I have never seen this syntax before. It also works when list [b, a]
precedes [a<b]
.
I would expect it to look like this
print( a if a < b else b )
Link to resource: https://www.geeksforgeeks.org/ternary-operator-in-python/