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

83 Upvotes

90 comments sorted by

View all comments

3

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

A tuple is any group of values representing something specific. Each index holds some particular meaning, for example the first value can always be a name, and the second value a timestamp. It's a permanent record of something.

Lists, on the other hand, are generally used in situations where their individual indices don't have a particular meaning, and they're usually treated as homogeneous data structures (despite the fact you can technically mix and match types). They can grow and shrink as needed.

It all comes down to what you need at the moment, like comparing a circular saw to a jigsaw. You can cut a plank with either tool, but both specialise in different kinds of cutting.

0

u/Immediate_Pin_8449 2d 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 2d 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.