Python Pass By Reference

I implemented a bare bones version of Tic Tac Toe using the Python programming language. Since my last post, I added logic so that the computer made moves during its turn. The computer AI is not too intelligent. It just follows a preset path, and skips over spots that are taken on the board. The goal here is to learn Python, not figure out the Tic Tac Toe bot.

During this exercise, I needed to finally figure out whether parameters passed to a function are by value or reference. The answer is not so simple. Let's get one thing out of the way first. If you pass a string to a function, it cannot be changed as that type is immutable. But let's discuss passing mutable types to a function.

When you pass a variable, you are supplying a name that is associated to an object. That name is like a reference. The function gets its own reference that is separate from the formal parameter name. However the version that the function has can be used to reference and change the object it points to. So that is kind of like passing by reference.

You can reassign the local function reference to some other object. However the original variable (reference) that the caller has is unchanged by this reassignment. Confused? I guess you got to play with it a bit to understand what the heck is going on here. I will just treat this as pass by reference with some caveats.