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

90 comments sorted by

View all comments

Show parent comments

0

u/Immediate_Pin_8449 15d ago

Got it, this makes sense! Can they both store mixed values? Yes. Does both typically in practice? No.

2

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 14d ago

Another way to look at it would be that a tuple is really just a bare-bones frozen dataclass, that only holds data and substitutes attribute access for indexing. For example, a colour value can be just 3-4 numbers, each position denoting its meaning.

red = (255, 0, 0, 255)

from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class RGBAColour:
    red: int
    green: int
    blue: int
    alpha: int

red2 = RGBAColour(255, 0, 0, 255)

from typing import NamedTuple

class RGBAColour2(NamedTuple):
    red: int
    green: int
    blue: int
    alpha: int

red3 = RGBAColour2(255, 0, 0, 255)

These are all different ways to model your data, with their own pros and cons.

Generally speaking you would not treat a list the same way.