r/learnpython • u/Pure-Homework681 • Mar 27 '23
Actually using a tuple
Can someone, please, give me a "real-world" example on the use of a tuple? I'm learning through w3schools. The idea of a tuple sort of makes sense, but I have no idea how it would/could be applied.
147
Upvotes
92
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Mar 27 '23 edited Mar 27 '23
Tuples are great, because immutability is great; they're hashable, meaning you can use them as dictionary keys or store them in sets, but perhaps more importantly you can cache them. This can be a big help when you have an expensive function that might receive the same arguments more than once and it doesn't have side-effects.
Furthermore, you can't accidentally swap values in a tuple, so they're great for constants.
I'd default to using tuples as data structures, unless you needed mutability (lists), wanted to avoid duplicates or compare unique values (sets), or wanted a clear mapping between arbitrary values (dictionaries).
Tuples and
collections.namedtupleessentially work as ad hoc classes, when the order of elements is enough to represent the data or a dataclass would be too much effort.EDIT: As an example, say we had one of those expensive function calls. For simplicity, here's a function that doubles numbers and returns them, after two seconds:
It's probably fine if it only needs to run once, but what if we're running it multiple times?
This would take 10 seconds to run. But since the function sees the same arguments repeatedly, if we just cache the results we can ignore most of the calculations; to do this, we can use
functools.cache."Okay, but... what does any of this have to do with tuples?" I hear you ask. Caches can't use mutable arguments, so if you were to give this function a list your program would crash. This is because you can't hash mutable objects.