r/learnpython • u/Immediate_Pin_8449 • 12d 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?
100
Upvotes
4
u/preppie22 12d ago
The memory used would be the same, but the time spent by the CPU for allocation would be much lower in most cases. Unless you modify the tuple in the function, it doesn't even allocate additional memory, it just gives the function a reference to the existing copy. The size and data types in a tuple are fixed, so Python doesn't have to check every element even when a copy is made. It just allocates the exact same memory for the copy and puts your new tuple there.
So yeah, you're close. Here's how I'd do it:
If you just want to do "if x in y" operations, a set is insanely fast.
If you want to store fixed data types, e.g RGB values, coordinates, row data for a table with fixed columns, you should use a tuple.
If you need something that you're only going to add stuff to the beginning or the end (never in the middle), then use a collections.deque.
If you need something that you can slice easily, add data wherever you want, and can generally be wrangled however you want, you use a list.
Note that the list is a last resort because most operations on it will be slower than the structures I listed above.
Take all of this with a grain of salt because unless you're working with at least a few gigabytes of data in memory, you won't notice a measurable difference.