I’m writing a parser, and in the process of debugging it, I found that apparently, this is legal Python:
for [] in [[]]: print 0
and so is this (!):
for [][:] in [[]]: print 0
I don’t blame the parser for getting confused… I’m having trouble figuring out how to interpret it!
What exactly does this statement mean?
In terms of execution: nothing.
The
forloop itself loops over an empty list, so no iterations will take place.And that’s a good thing, because the
for []means: assign each entry in the loop to 0 variables. The latter part is probably what is puzzling you.The statement is legal because the target token
token_listallows you to assign the values in a sequence to an equally large sequence of variable names; we call this tuple unpacking. The following are more useful examples of target lists, in assignment and deletion:You can do the same in a
forloop:You can use both tuples and lists for the
target_listtoken, this is legal too:However, in Python, a list can be empty. Thus, the following is legal, however non-sensical:
and finally, so is this:
More fun with target lists:
Now the left-hand side is using a slice in the assignment. From the documentation:
So here we are no longer using tuple unpacking; instead we replace a section of the left-hand list with the right-hand list. But because in our example the left-hand list is an anonymous list literal, the resulting altered list is lost again.
But because such an assignment is also legal in a for loop, the following is legal syntax, albeit rather non-sensical: