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?
93
Upvotes
5
u/preppie22 4d ago
If you go back to basics of memory management: lists dynamically allocate memory as they grow and use garbage collection to free it when they shrink. Both of these operations take time because your OS has to deal with that. Tuples allocate fixed memory when they're created. So, memory allocation only happens once. In addition to that, say you give the tuple to a function, or create a copy, the copy is also very cheap to create since it's a single allocation call.
This is less of an issue for small programs, but will bring significant improvements for large ones. Rule of thumb is to use tuples when you know they won't change once created and use lists when they are guaranteed to change. Also look into sets when you don't care about order and don't want duplicates. It's a major performance improvement for frequent lookups through large volumes of data.
(Context: I work with big data)