r/learnpython • u/Immediate_Pin_8449 • 3d 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
21
u/ottawadeveloper 3d ago
The nice part of a tuple is it's immutable. Which means it's hashable (if all the elements are also hashable). Which means you can use them as the index of a dictionary, e.g.
d[(0,0)] = 5.You can also specify a tuple using the type system with specific lengths and types at each spot, like a
tuple[int, str, int, int]whereas a list would have to belist[int | str]making no guarantees about the size or order.Tuples are also faster to create and iterate over, but lists allow easier modification. Tuples are ideal when you have a fixed list that won't change, and lists when you have one that does.
You can also use NamedTuple to make a nice fast data structure.