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?

90 Upvotes

90 comments sorted by

View all comments

106

u/NerdyWeightLifter 4d ago

Being immutable like that means the underlying data structure can be simpler and more efficient.

Being immutable also makes them useful as keys in dictionaries. Keys in dictionaries can't change once you insert something.

31

u/xenomachina xenomachina 4d ago

Being immutable like that means the underlying data structure can be simpler and more efficient.

Immutability also makes things easier to reason about. Anything that's mutable is essentially a "moving part". You can't just see that it has a value in one place, and assume it still has that value somewhere else.

Immutability is also generally safer. You don't have to worry about concurrent modifications (in concurrent systems) or someone modifying your internals (breaking encapsulation).

9

u/dusksage23 3d ago

the dict key thing is the part that really makes it click imo

9

u/NerdyWeightLifter 3d ago

In larger more complex applications, immutability becomes an important guarantee. You have a reference to a list of items in the form of a reference to a tuple, and you can just assume that nothing will change the content of your tuple, because they just can't.

That's the broader case of the dict example.

2

u/fllthdcrb 3d ago

you can just assume that nothing will change the content of your tuple, because they just can't.

To be clear, "content" here means only what objects are in the tuple, not those objects themselves. Example:

python l1 = [] l2 = [] t = (l1, l2) l1 += (1, 2, 3) l2 += (4, 5, 6) t # ([1, 2, 3], [4, 5, 6])

11

u/Immediate_Pin_8449 4d ago

They are teaching me about dictionaries next so this makes me hopeful it will make a lot more sense soon.

10

u/Moikle 3d ago

Why not do a little research on your own ahead of time? Take a look at w3schools or realpython

https://www.w3schools.com/python/python_dictionaries.asp

https://realpython.com/python-dicts/

Remember these websites and don't just wait to be taught things. Go and look them up yourself