I ran across some python code syntax that I have never seen before. Here is an example:
i = 0
for spam in range(10):
i += [1, 3][i > 5]
print(i)
The result is the sequence of 1,2,3,4,5,6,9,12,15,18. So, it increments by 1 until i > 5
, then increments by 3 thereafter.
Previously, I would have written the line as:
if i > 5:
i += 3
else:
i += 1
So what is the line: i += [1, 3][i > 5]
?
The syntax is interesting and I wanted to read more about it, but don't know where to look.
Edit:
Thank you Darkstarone. I had never thought of using an expression to return a list index. That is very cool. This means you could also do things like: spam = ["Even", "Odd"][eggs % 2]
to return an even or odd string or foo = ["A", "B", "C"][zot % 3]
to cycle through three choices when looping through values of zot.
Probably won't make a habit of using this construct since other expressions are easier to understand. But, I'll take this into the bag o' tricks for that perfect situation.
So what I believe is happening here is the list ([1,3]
) can either be:
[1,3][0] # 1
Or
[1,3][1] # 3
It's taking advantage of the fact that 0 == False
and 1 == True
. It's rather neat, although a little opaque. I probably would have written it like so:
i = 0
for _ in range(10):
i += 3 if i > 5 else 1
print(i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With