tuples, index method, Python's design

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Apr 14 04:22:01 EDT 2007


On Sat, 14 Apr 2007 08:19:36 +0200, Hendrik van Rooyen wrote:

> This is the point where the whole thing falls apart in my head and 
> I get real confused - I can't find a reason why, list or tuple, the first
> item can't be something, the second something else, etc...

It's not that they _can't_ be, but that the two sequence types were
designed for different uses:

Here are some tuples of statistics about people:

fred = (35, 66, 212)  # age, height, weight
george = (42, 75, 316)

They are tuples because each one is like a Pascal record or a C struct.

It isn't likely that you'll be in a position where you know that Fred's
age, height or weight is 66, but you don't know which one and so need
fred.index() to find out. Hence, tuples weren't designed to have an index
method.

Here are some lists of statistics about people:

ages = [35, 42, 26, 17, 18]
heights = [66, 75, 70, 61, 59]
weights = [212, 316, 295, 247, 251]
# notice that the first column is fred, the second column is george, etc.

They are mutable lists rather than immutable tuples because you don't know
ahead of time how many data items you need to store.

Now, it is likely that you'll want to know which column(s) have an age of
26, so lists were designed to have an index method.

Now, that's the sort of things tuples and lists were designed for. If you
want to use them for something else, you're free to.



-- 
Steven.




More information about the Python-list mailing list