Lists and Tuples
Duncan Booth
duncan at NOSPAMrcp.co.uk
Fri Dec 5 04:25:58 EST 2003
Jeff Wagner <JWagner at hotmail.com> wrote in
news:f570tv43pa27td77188ljkk87vl19gif6p at 4ax.com:
> From what I can see, there is no reason for me to ever want to use a
> tuple and I think there is something I am missing. Why would Guido go
> to all the effort to include tuples if (as it appears) lists are just
> as good but more powerful ... you can change the contents of a list.
The most practical difference (if you don't need to modify the contents) is
that tuples can be used as dictionary keys, but lists cannot. There is a
minor performance difference, in particular tuples will take less memory so
if you have a few million of them kicking around your application you might
notice the difference.
However, as other posters have suggested the best way to look at it is
often to use tuples when you have a fixed number of objects, possibly of
different types, e.g. a database record. When you have a variable number of
objects (usually of the same type, or supporting a similar interface) then
a list if obviously better. If you have a variable number of groups of
objects, then a list of tuples seems to fit best. In any of these cases you
could use a list in place of the tuple, but the distinction can help keep
things clear.
Bottom line:
If you are primarily reading the sequence using constant indices, then use
a tuple. If the code starts looking messy then consider defining a class to
replace the tuples and using fieldnames instead of constant indices.
If you need to use the object as a dictionary key, or if you have reason to
be concerned about memory use (because there are a lot of them) use a
tuple.
Otherwise use a list.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list