r/learnmachinelearning • • 8d ago

Python Mutability: tuple vs list

Post image

An exercise to help build the right mental model for Python data.

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

4 Upvotes

6 comments sorted by

3

u/SteamEigen 8d ago

Today I learned that you can add to a tuple. I expected it to be more immutable.

8

u/crayphor 8d ago

I think it's more that += does a concatenation, then an assignment. It is not editing the tuple, it is creating a new tuple and assigning it as the value of the variable.

1

u/Sea-Ad7805 8d ago edited 7d ago

"Immutable" does not mean "constant", it means if you change it a copy is made so the old value is preserved. Same with immutable int and str:

a = 100
b = a
b += 11
print(a)

s = "hello"
t = s
t += " world"
print(s)

See visualization by memory_graph.

1

u/Ok-Definition8003 7d ago

Why did we let such nonsense become the de-facto language SMH

1

u/Sea-Ad7805 6d ago

There are good reasons for this, and we see similar decisions in other languages like Java, JavaScript, Kotlin, Ruby, ...

Why mutable and immutable types? Python immutable types generally have a hash function, so you can add them as key to a set/dict. Mutable types generally don't have a (default) hash function, as they can change value after adding to a set/dict, and that would mean they are then stored in the wrong index/bucket and can't be found anymore.

How would you like to design the data model if you don't like Python's?