List vs tuples
Roy Smith
roy at panix.com
Fri Apr 9 09:42:01 EDT 2004
Isaac To <kkto at csis.hku.hk> wrote:
> And you can use a list here as well. Indeed, if you want to emulate C
> struct, you probably will use list instead of tuples, since in C, structs
> are mutable.
It's a bit of a misnomer to say that tuples (or lists) emulate C
structs. You access the elements of a struct by name, but you access
the elements of a tuple by index. A much better emulation of a C struct
is a degenerate class with no methods. If I wanted to emulate:
struct myData {
int x;
int y;
} datum = {1, 42};
I'd do something like:
class myData:
pass
datum = myData()
datum.x = 1
datum.y = 42
The reason people sometimes think of tuples as struct-like is because
they are often used to return multiple values from functions. To use
the example often cited, you might do:
x, y = getCoordinates()
where getCoordinates() returns a tuple of two numbers. It sort of looks
like a struct because it's got x an y "members", but the x and y names
are assigned in the unpacking operation, they're not inherent in the
object returned. A more "struct-like" way of doing it would be to have
getCoordinates() return something like the myData object shown above.
Then you'd have:
point = getCoordinates()
and you could make use of point.x and point.y in your code.
I'm not saying that the idea of returning a tuple and immediately
unpacking it isn't handy. It certainly is, and I use it often in the
code that I write. But, I think saying that it emulates a C struct
gives people the wrong idea of what's going on.
More information about the Python-list
mailing list