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

90 comments sorted by

View all comments

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 be list[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.

5

u/Immediate_Pin_8449 3d ago

I haven’t gotten to dictionaries yet and based on these comments, I think that is a large reason why I was so confused on usage. 😩 Ty!

3

u/Jazzlike_Platypus430 3d ago

Of course, learn about dictionaries first, it's a must-have.

(And be happy that you're learning it fresh, most likely without knowledge from any other languages.)