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

64 comments sorted by

View all comments

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.namedtuple essentially 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:

import time


def expensive_calculation(nums: tuple[int, ...]) -> tuple[int, ...]:
    time.sleep(2)
    return tuple(num*2 for num in nums)

It's probably fine if it only needs to run once, but what if we're running it multiple times?

for _ in range(5):
    print(expensive_calculation((2, 3, 5, 7, 11)))

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.

import time
from functools import cache


@cache
def expensive_calculation(nums: tuple[int, ...]) -> tuple[int, ...]:
    time.sleep(2)
    return tuple(num*2 for num in nums)

for _ in range(5):
    print(expensive_calculation((2, 3, 5, 7, 11)))  # Takes about 2 seconds now

"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.

-16

u/teepidge Mar 27 '23

Dude. Too much. I feel like someone asking for a real world example or using a tuple can't follow this. I say that because that's me... Looking for a real world example and I can't follow this at all.

14

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Mar 27 '23

Perhaps. You're welcome to try and give a simpler answer, my sleep-deprived brain couldn't come up with a better one on the spot.

-2

u/teepidge Mar 27 '23

No I mean I was hoping for a simpler answer because I struggle with the concept, too. I appreciate the depth, but I think in the learn python subreddit, the average user is more novice level, and your answer went above and beyond. I can see myself bookmarking it and returning to it when I have a better understanding of what you're talking about!

12

u/HelpfulBuilder Mar 27 '23

Well the real answer is that at your level there isn't much difference. I program with python almost every day and 99% of the time I could use either one.

He had this somewhat complicated example bc there aren't many examples.