Using tuples correctly?

Robert Brewer fumanchu at
Mon Oct 11 06:01:16 CEST 2004

BJörn Lindqvist wrote:
> I like tuples alot. But in some situations you seem to be forced to
> access the elements of a tuple via its indexes and that is pretty
> ugly. For example:
> # make_color() returns a rgb tuple (r, g, b). I.e. (255, 0, 0)
> print "The red value is: ", make_color()[0]
> Not nice at all. It is maybe OK for a rgb tuple that only has three
> elements, but for a tuple that has 10+ elements, index access is
> rediculous. In that case, unpacking wont helpe either. What you would
> like to write is:
> print "The red value is: ", make_color().r
> After some more browsing of the Python Cookbook and googling it seems
> like lots of people is trying to emulate structs on the fly in python.
> So why aren't there a tuple-with-named-attributes type in python?

The tuple-with-named-attributes is called a 'class' in Python.

class RGB(object):
    def __init__(self, r=0, g=0, b=0): = r = g = b

> So you could write stuff like this:
> return (r: 10, g: 20, b: 30) or maybe return (.r 10, .g 20, .b 30)

color = RGB(10, 20, 30)
print "The red value is: ",

If you *must* have a tuple to throw around, give your class a 'tuple' method:

class RGB(object):
    def __init__(self, r=0, g=0, b=0): = r = g = b
    def tuple(self):
        return (self.r, self.g, self.b)

Why bother to shoehorn all of the name scaffolding into tuples when it's already present in classes?

Robert Brewer
Amor Ministries
fumanchu at

More information about the Python-list mailing list