Simple Python code with weird list manipulation/comprehension technique by which one element of the list gets assigned to a variable
Question:
Today I was browsing through a coding website and found a simple code in Python which I was having a hard time to comprehend.
Below is the exact code (with extra details added as comments):
x = -23
sign = [1,-1][x < 0] # -1 if x is negative and 1 if x is positive
print(sign) #outputs -1 since x=-23 is negative
Can anyone please help me understand how this code is working and what this technique is called (I presume it is some kind of list comprehension/manipulation)?
Answers:
This is playing with the fact that True
is equivalent to 1
and False
to 0
.
If x<0
returns True
, then [1,-1][x < 0]
is equivalent to [1,-1][1]
, and thus -1
.
The logic is the same when x<0
returns False
: [1,-1][0]
-> 1
sign = [1,-1][x < 0]
is just a fancy way to write
if x < 0:
sign = -1
else:
sign = 1
x < 0
is either True
or False
. Since True == 1
and False == 0
you can use booleans to index into the list [-1, 1]
.
x = -23
x2 = 23
sign = ["false","true"][x > 0]
sign2 = ["false","true"][x2 > 0]
print("sign:",sign)
print("sign2:",sign2)
the result is sign:false,sign2:true
Today I was browsing through a coding website and found a simple code in Python which I was having a hard time to comprehend.
Below is the exact code (with extra details added as comments):
x = -23
sign = [1,-1][x < 0] # -1 if x is negative and 1 if x is positive
print(sign) #outputs -1 since x=-23 is negative
Can anyone please help me understand how this code is working and what this technique is called (I presume it is some kind of list comprehension/manipulation)?
This is playing with the fact that True
is equivalent to 1
and False
to 0
.
If x<0
returns True
, then [1,-1][x < 0]
is equivalent to [1,-1][1]
, and thus -1
.
The logic is the same when x<0
returns False
: [1,-1][0]
-> 1
sign = [1,-1][x < 0]
is just a fancy way to write
if x < 0:
sign = -1
else:
sign = 1
x < 0
is either True
or False
. Since True == 1
and False == 0
you can use booleans to index into the list [-1, 1]
.
x = -23
x2 = 23
sign = ["false","true"][x > 0]
sign2 = ["false","true"][x2 > 0]
print("sign:",sign)
print("sign2:",sign2)
the result is sign:false,sign2:true