Skip to content
Fullstack Launchpad

What Mutable and Immutable Mean: Values, References and Hashability

Two variables can refer to the same object. That affects how you update data, compare values and choose keys for a hash table.

By Published 6 min read

Two names for one shopping cart

A shopper has tea in their cart. You save the cart for an Undo button, then add lime to the open cart. What does this code print?

python
cart = ["tea"]
saved = cart
cart.append("lime")
print(saved)
# prints: ['tea', 'lime']

The assignment gives the list a second name. When append adds lime, both names show the extra item. Undo needs the cart as it was before the edit. The same question comes up when you store a key in a hash table. What did the assignment preserve, and what can still change?

SectionExampleResult
Values and references["tea"] == ["tea"]Two lists with equal contents
Mutable and immutable objectscart.append("lime")Anyone holding the same list sees the new item
Hashable keyshash((["tea"], 1))An error because the tuple contains a list

Value and reference

A value is what an expression represents. Assign an integer of type int in Go and the destination gets a copy of the number. A reference is itself a value. Copying it gives you access to the same object through a second variable. Having two ways to reach the same data is called aliasing. Copying a reference stays cheap even when the cart contains a thousand items.

In Python, assignment binds a name to the object on the right. Suppose two shoppers each order tea. To check whether their carts contain the same items in the same order, use == to compare the lists by value. To find out whether editing one list will also edit the other, use is to check whether the names refer to the same object.

python
cart = ["tea"]
other = ["tea"]
print(cart == other)
# prints: True
print(cart is other)
# prints: False

For the Undo button, if each item is just a string, you can build a new list when adding an item. Here + joins two lists and returns a new one. The assignment binds cart to that list. The name saved still refers to the original.

python
cart = ["tea"]
saved = cart
cart = cart + ["lime"]
print(saved)
# prints: ['tea']

Mutable and immutable objects

A list is mutable. You can replace an item while another shopper still holds a reference to that very list. A string is immutable. When you rename an item from "tea" to "iced tea", anyone who kept the original string can still read the old name.

With nested data, it matters which object carries that guarantee. A Python tuple is a sequence with fixed slots. The comma in (items,) creates a tuple with one element. You can't replace the list in that slot with another list. You can still add items to the list it holds.

python
items = ["tea"]
order = (items,)
items.append("lime")
print(order)
# prints: (['tea', 'lime'],)

Reading configuration across threads. Suppose each worker receives the same configuration before it starts processing orders. If the configuration is the tuple ("VND", 30000), holding a currency code and a shipping fee, no worker can edit either value. They can read that configuration without a lock. Replace the amount with a list of fees and edit that list, and the guarantee disappears. If the configuration changes while workers are running, the new version still needs a safe handoff between threads.

Preserving React state. Suppose the cart state is { items: ["tea"], note: "" }. Calling push on items leaves both the previous and the next render pointing at the edited array. With setCart as the state setter, build a new cart instead of editing the old one:

js
setCart(old => ({ ...old, items: [...old.items, "lime"] }));

The outer ... copies the cart's properties. The inner ... copies the items into a new array. The previous render and the Undo button keep the original cart. Adding an item now costs a copy of the array's elements. Parts of the cart you leave alone can stay shared. React on updating objects in state (opens in a new tab)

Hashable keys in a hash table

A hash table uses a key's hash to narrow down where to look. It then checks candidate keys for equality. Different keys can have the same hash. Equal keys must always have equal hashes. In Python, a hashable object follows that rule and keeps the same hash throughout its lifetime.

Consider a shipping rate table indexed by region and weight. The pair ("HN", 1) is a tuple containing a string and an integer, both hashable. A later request can reconstruct that pair from its own inputs and retrieve the stored fee. In Python, {key: value} creates a dictionary, and fees[key] retrieves the value for that key.

python
fees = {("HN", 1): 30000}
city = "HN"
weight = 1
print(fees[(city, weight)])
# prints: 30000

If a key's hash depended on a weight someone changed after insertion, the next lookup could search the wrong part of the table. Python rejects lists as keys up front. Wrapping a list in a tuple still leaves the list inside. You can try this directly with hash, the function that returns a hash value.

python
print(hash((["tea"], 1)))
# error: TypeError: unhashable type: 'list'

A mutable object can also make a valid key. An instance of a Python class that uses the default identity-based equality and hash can serve as a key even if its attributes change. Identity distinguishes individual objects. Using identity for the shipping lookup would treat two separately created requests as different keys. The region and weight express what makes two requests equivalent for this rate table.

For example, a delivery ticket can change status between dispatch and arrival. With the ticket itself as the key, you can still look up its fee after updating the status. A newly created ticket has a different identity. Here the class body contains only pass, so the class inherits the default equality and hash.

python
class Ticket:
    pass

ticket = Ticket()
fees = {ticket: 30000}
ticket.status = "delivered"
print(fees[ticket])
# prints: 30000
print(Ticket() in fees)
# prints: False

A cache hit can return yesterday's price. Suppose the cache holds 30000 for ("HN", 1). When the carrier raises its fee, the key is still hashable and the cache can still find the old price. If the result depends on the rate table version, include that version in the key, as in ("HN", 1, "v2"), or clear the old result when the rates change. A stable hash helps retrieve the entry. Which inputs you include determines whether you can reuse the result.

What each language shares on assignment

LanguageStrings and sequencesAssignment or use as a key
PythonA str is immutable, a list allows edits, and a tuple has fixed slots.Assignment binds another name to the same object. A tuple can be a key if every element is hashable.
JavaA String is immutable. Arrays and ArrayList allow element updates.A final reference stays fixed after assignment. A record can hold a mutable list.
JSPrimitive strings are immutable. Arrays allow edits.Object.freeze acts directly on the object you pass. A Map accepts object keys by identity.
GoA string is immutable. Array assignment copies each element. Slices can share a backing array.Struct assignment copies the fields. Copying a pointer leaves both pointers addressing the same data. Map keys must support equality.

Key takeaways

  • When saving a value for later, consider who can still edit the data you need.
  • A snapshot for Undo needs the old array of items intact, not just a reference to it.
  • A hash table key needs the fields used for equality and hashing to stay stable.

Sources