[Solved] Why are python lists not local


Well, technically, you’re right in that the piano variable is local. However, it still points to the same internal reference as pizza.

This is what’s happening behind the scene:

You allocate a new list of values, and a variable named pizza is created so you can refer to it:

pizza -> [ 1 , 2 ]

When you assign this variable to another variable, only the pointer to the reference is copied, but the reference itself remains.

 other_var = pizza

 other_var -
            |
 pizza -----|--> [ 1 , 2 ]

So, when you pass in pizza to the function f technically, you are just copying only the pointer to the same list, and creating a different named variable to reference.

Yes, this newly created variable can only be accessed within the f scope, so yes, it’s local. But if you mutate its reference in any way, it’d be as if you were mutating pizza itself as they both point to the same object.

3

solved Why are python lists not local