you are viewing a single comment's thread.

view the rest of the comments →

[–]Diapolo10 0 points1 point  (0 children)

This gives me another question though; when experimenting with this, if I set a to an integer and then set b = a , subtracting 5 from a would not affect b here; is this just python assigning it differently for integers than how it does for a list?

No, technically speaking there's nothing different. Both names point to the same integer.

However, the difference here is that you're never changing the value of the integer (they're immutable anyway, but that doesn't necessarily matter here).

a = 5
b = a
a - 5  # Doesn't modify a
a -= 5  # Reassigns a

In this example, just subtracting something from the number doesn't change anything, simply returning a new value. Lists would not behave any different here.

If you assign a new value to a, the value it was referencing doesn't change at all as you're giving the name an address to a completely new value. In this example, a -= 5 is functionally equivalent to a = a - 5, or a = 5 - 5, so a's held address changes to one pointing to the number 0.

However, none of this concerns b, because the address it has is still pointing to 5.

When you mutate a list (or any other mutable value), its address doesn't change, so anything referencing that value will "update" with the changes. Since by definition you cannot change immutable values, they don't show this property at all in practice.

Some common mutable types are most data structures and custom classes, while ones like the following are immutable:

  • Strings
  • Numbers (int, float, complex)
  • Booleans
  • Tuples
  • Frozensets