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]?
- What do you call that syntax structure?
- Is it some form of list comprehension or something else entirely?
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.
True == 1andFalse == 0. It's not a list comprehension, that would haveforandin. It's also not a great way to write it due to exactly your current confusion, vs. a more straightforward ternary expression.i > 5 and 3 or 1) and "the actual conditional expression syntax" (3 if i > 5 else 1).[[1,3][k > 4], [4,5][k>6]][k > 6]