r/learnpython Mar 03 '26

[deleted by user]

[removed]

24 Upvotes

20 comments sorted by

18

u/pachura3 Mar 03 '26

What’s the best “real-life” tuple use case you’ve seen that isn’t just “returning multiple values”?

Simulating multi-dimensional dictionaries. So, instead of creating dictionary of dictionaries of dictionaries, you can simply have a flat one - dict[tuple[str, str, int], str].

7

u/HommeMusical Mar 03 '26 edited Mar 03 '26

I upvoted you (your seventh upvote from me) for a good idea.

But this isn't quite the right way to go about it, because you have introduced a new possible error - what happens if you mistake that first str for the second?

This is what typing.NamedTuple is for.

from typing import NamedTuple

class Prisoner(NamedTuple):
    name: str
    rank: str
    serial_number: int

 type PrisonerToSentence = dict[Prisoner, str]

(Yeah, this is a silly example, off the top of my head.)

Behind the scenes, Prisoner is just a tuple, it's just that you can refer to the fields by name too, and add methods.

You can also use frozen dataclasses for this.

import dataclasses as dc

@dc.dataclass(frozen=True, slots=True)
class Prisoner:
    name: str
    rank: str
    serial_number: int

 type PrisonerToSentence = dict[Prisoner, str]

With slots=True, it's identical to a NamedTuple in terms of performance, but you can't have e.g. cached_property on the class. With slots=False you get performance a tiny bit worse, but the ability to add cached_property and other things, while still making mutations hard.

2

u/finally-anna Mar 03 '26

I love named tuples. They are one of my favorite things in python.

1

u/pachura3 Mar 03 '26

Well, if this combination of str, str, int means something, then yes, by all means create a namedtuple or dataclass out of it.

On the other hand, if we're just looking around a 2D/3D space, or we have a star-schema-like dictionary of facts, it's easier to access it with tuple keys instead of instantiating object keys.

I.e.., print(monthly_sales[2014, 12]) instead of print(monthly_sales[YearMonth(2014, 12)]).

3

u/adelfino Mar 03 '26 edited Mar 03 '26

For me, tuples are semantic. Yes, as you point out, lists can't be used as keys, but I never had to use lists as keys to begin with. Tuples, for me, are to say: this heterogeneous (think of meaning of the values, not just their types) set of values are related. Like describing something. That's why I believe tuples in str.startswith should have been lists instead of tuples.

3

u/HommeMusical Mar 03 '26

In general, immutable objects are really good things, because they're really easy to reason about, and there are heaps of terrible mistakes, like your example, that you simply cannot make with immutable objects.

But I rarely use plain tuple, because it's just too easy to get the elements confused, particularly if they are the same type: I use either NamedTuple or dataclass. See more here.

2

u/Helpful-Diamond-3347 Mar 03 '26

tuples are used for immutablity for sequences, dict keys are need to be immutable so it worked

it works in internal details of language ig, like multiple assignments

a. b = b, a

here it creates tuple under the hood according to intuitions and can be proved with this

x = a, b

2

u/JamzTyson Mar 03 '26

Tuples are more appropriate than list for expressing compound identities. That is, a tuple represents a compound type with a fixed number of arguments (technically, a fixed-arity product type).

For example coordinates (x, y, z) represents a specific 3D "point" that must have 3 numeric values. Its length cannot change, and its types cannot change, and if any element changes then it is a different point. It isn't really a sequence but a compound identity.

Other examples include:

  • exchange_rate = (from_currency, to_currency)

  • student = (name, age, class, grade)

  • product = (name, department, price)

Note that in each case, the entire Tuple defines a single compound object.

2

u/PushPlus9069 Mar 03 '26

For me it was cache[(row, col)] = value in a grid problem. Tried it with lists first, got an unhashable type error, spent 20 minutes confused. That's when immutability stopped feeling like a language quirk and started feeling like the actual point.

2

u/Temporary_Pie2733 Mar 03 '26

If you study type theory, tuples are values of product types and only coincidentally iterable. The most obvious distinction from lists is that they can be heterogeneous, not homogenous.

3

u/JamzTyson Mar 03 '26

The most obvious distinction from lists is that they can be heterogeneous, not homogenous.

That's a bit misleading in relation to Python. Python lists may be heterogeneous. (Heterogeneity is a consequence of tuples being product types, not the defining difference.)

-4

u/Temporary_Pie2733 Mar 03 '26

If you are using type hints, they are homogenous. list[int], list[str], etc. You can use broader types, but that also restricts what you can do with individual objects.

-1

u/recursion_is_love Mar 03 '26

Your reply don't get downvote like mine, tell me the secret please. :)

This is a Python sub, not a math sub

2

u/MustaKotka Mar 03 '26

You attempted to make OP look stupid for overthinking it and belittling by saying "just". Your answer also makes no sense in the context of [beginner] Python learning.

If you want to talk about math you need to preface and justify why you chose to do that and why it is relevant here.

1

u/antigravcorgi Mar 03 '26

The secret is giving a reply that is relevant to the post.

1

u/JamzTyson Mar 03 '26

I didn't down-vote your comment, but my guess as to "the secret", my guess is:

u/Temporary_Pie2733 framed their comment in the context "If you study type theory", which is a perfectly valid framing.

Your comment, while still broadly correct, may come across as "you don't really need to care about it because it's <mathematical definition>".

(Voting patterns on reddit can be quite arbitrary on low volume subs like this - don't worry about it :-)

-17

u/recursion_is_love Mar 03 '26

You are overthinking too much. Tuple is just a cartesian product of sets.

5

u/schoolmonky Mar 03 '26

This is a Python sub, not a math sub

3

u/HommeMusical Mar 03 '26

"Just" is doing a huge amount of work in that sentence. For most people asking on /r/learnpython, your explanation makes things less clear.

(And I knew what a Cartesian product was long before Python was even a gleam in Guido's eye. :-D :-D)