First For Those Who don't know Ternary Operation
Ternary Operator is a easy and consize way of if-else
Ok So lets flex some JS muscles.
The syntax in JS is something like this.
let v = condition ? "True" : "False"
Here if condition is true.
The value of the variable v becomes True.
While if condition is false.
The value of the variable v becomes False.
In Python's if-else it would be.
if condition:
v = "True"
else:
v = "False"
Now To Emulate This in Python ?
ifTrue = "It is a True Value"
ifFalse = "It is a False Value"
trueValue = 432
c1 = [ifFalse, ifTrue][bool(trueValue)]
Understanding The Code
So in simple if else it would be like this
if trueValue:
c1 = ifTrue
else:
c2 = ifFalse
So How is this Happening?
Now lets break it into pieces
c1 = [ifFalse, ifTrue]
is a List. Do you agree?
c1[0] would be ifFalse.
c2[1] would be ifTrue.
Agreed?
Now,
bool(3)
will give True in python
bool(None)
will give False in python
Shall We Move on ?
Ok So
a = [ifFalse, ifTrue]
c = a[bool(trueValue)]
here if bool(trueValue)
is True
then it will get typecasted to integer which is 1.
And, Whats a[1] it's ifTrue
.
While it its False
. It will get typecasted to a[0] which is ifFalse
.
This was a Long One but for short and helpful tricks
Follow PythonZen On Instagram
Top comments (4)
I love this, but at the same time I hate it 😂
Reminds me of how you can index arrays in C as
19[arr]
(get the 20th element of thearr
array) because it just gets translated to*(19+arr)
Is it pretty? No.
Does it make the language look good? No.
Is it fun though? Hell yea!
Yeah, I hated the syntax but loved it at the same time.
Why not just do this? 🤷♂️
Actually, I know this is better. But just wanted to show some python power to you