The dictionary returned by locals() is not a view of the function's locals, but a copy. Therefore, modification of the dictionary returned from locals() will not modify the local variables of the function.

If the intention is to modify a local variable, then do so directly.

In this example, rather than assigning to the variable z directly, the dictionary returned by locals() is modified.

  • Python Language Reference: The for statement.
  • Python Tutorial: for statements.