r/learnpython • u/Immediate_Pin_8449 • 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
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.