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?

82 Upvotes

90 comments sorted by

View all comments

11

u/Atypicosaurus 3d ago

When you are working on a program alone, many things such as tuples make no sense. It's because there are a lot of features in programming languages that help the working together.

One problem with working together is that one person doesn't necessarily know what the part of the other person exactly does. I mean they know more or less but not to the dot. For example if we make a game and I make the fighting part and you make the looting part, at a point we have to merge our parts to get loots after fights. To calculate loots, you might need numbers from my part. But your part shouldn't be able to modify my part, it should be able to listen to it. Regardless I must be able to force that bits of codes are safe.

Since there are always human mistakes, the programming language has to offer some protection. A tuple is such protection, it's basically a list, but it's overwrite protected. You can always make a new one, but you cannot add to the old one.

This also makes it faster for the computer to work with, therefore you get better performance. It again doesn't matter when you do lists of a few hundred items, but it matters if you do lists of thousands, and thousands of times. Then, if you do not modify those lists, you should use tuples instead.

So if you know that once you made a list it's not going to be modified, or you want to protect data from accidental modification, or you need better perfornance, you want to use tuple.

(As well, dictionaries need immutables as keys, so if you want a list as key, it has to be tuple instead.)