Resources on explaining variable reassignment

Basically, I am wondering when am I supposed to assign a variable back to itself after applying a method/function to it, vs. simply applying the method. I generally always do the former. To illustrate, I want to know when to do:

a = a.strip()

and when to do:

a.strip()

But obviously not just for strip, and not for one specific object type.

Objects or data containers in Python can either be mutable or immutable.

For example, a tuple is immutable.

a = (1, 2)

If I wanted to change the 1 above to a 3, I won’t be able to. Python will throw an error. That’s what immutable means. We can’t change the values stored in those objects or containers (like a tuple).

However, some are mutable. Like lists.

a = [1, 2]

We can easily do -

a[0] = 3

And the above will change the values in a accordingly.

This is what marks the distinction. Underneath, it’s all to do with what is being stored in what bit of memory. Not something to go into detail at the moment.

When an object/data container is immutable then in order to modify it you have to re-assign it back to itself.

And when it’s mutable then some functions/methods can modify that object/container in-place.

So, it’s just a matter of knowing which ones are immutable and which aren’t. Which is not too difficult either. Mostly you need to know -

  • Mutable - list, dictionary, set
  • Immutable - int, float, decimal, bool, string, tuple

The above gives a broad overview of this. There might be instances where you will have to rely on simple googling and learn basic debugging skills to quickly identify whether what you are working with requires reassignment or not.

1 Like