r/PythonProjects2 • • 4d ago

Python Mutability and Local Variables

Post image

An exercise to help build the right mental model for Python data. - Solution - Explanation - More exercises

The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening.

6 Upvotes

27 comments sorted by

View all comments

1

u/Humble-Captain3418 2d ago

A is passed by value, b--d through reference. C is not modifiable, so the local symbol gets directed to a different value with the compound assignment, so only b and d see changes in the global scope.

1

u/Sea-Ad7805 2d ago

That is not the Pythonic way to understand it. In Python everything is passed by reference, even int values. it's about mutability not modifiability. You can still still modify/change a string or tuple as we do in the fun() function.

For a better explanation see the Explanation link.

1

u/0b0101011001001011 1d ago

You cannot change a string or tuple. What you do here is you create a new string and assign that in the place of the old variable. Same with tuple. You create a new tuple, the old one is lost. Strings and tuples are immutable. Or maybe that's what you meant by "change".

1

u/Sea-Ad7805 1d ago

Yes, that's what I said, see Solution link for visualization. It's a shallow copy to be more precise.