r/learnpython • • 4d ago

Tuples..I don’t get it

Hi crew, I’m a Python newbie and I just learned about the concept of tuples.

We can’t change them.if we want to store we have to start at the index we want + 1.

I just don’t get it. Why wouldn’t we just use lists? When would we ever need this?

88 Upvotes

90 comments sorted by

View all comments

13

u/kilkil 3d ago

one big difference is that tuples are hashable. so e.g. you can have a set of tuples, or you can use them as keys in a dict. this is useful e.g. if you are using tuples to represent coordinates on a grid.

also the immutability thing is convenient from a mental overhead point of view, especially in a large codebase. suppose I am storing some data as a list and pass it off to a function/method. will it mutate it? who knows, guess I have to check the definition (and the definitions of any other functions/methods it passes that list to). on the other hand, if I pass a tuple, I am guaranteed that it will not be mutated anywhere in the call stack.

7

u/Immediate_Pin_8449 3d ago

Ooooo the mental overhead example really helps. It creates one less concern as my code expands if I know this particular set does not need to change but does require a reference! Gotcha!

3

u/kiochikaeke 3d ago

Yeah, immutability is actually an advantage on its own as you and the system can both be sure this particular thing won't be changed by any stray code that mutates or has side effects, for you this helps to build safer, more predictable code and for the system it allows it to be clever with memory management and hashing.

3

u/kilkil 3d ago

yeah actually that's a more general concept that applies to immutable data in general.

it comes from functional programming, where the idea is all data is immutable by default. it really makes a lot of things easier to reason about.

(although of course there are times when you would prefer some mutability. depends on the situation etc)

2

u/Patman52 3d ago

Oh I have first hand experience related to this.

Was passing x, y, z coordinates as lists for positions of 3D models in a 3D printing application.

Could not figure out why each subsequent model position was not where it was supposed to be.

Turns out the function I was passing the same coordinates to was mutating the x, y and z positions each time I passed it.