Tuple question

Donn Cave donn at drizzle.com
Fri Sep 3 07:28:58 CEST 2004


Quoth Dan Christensen <jdc at uwo.ca>:
| I'm not sure I buy the arguments against an index operation for
| tuples.  For example, suppose we were conducting a vote about
| something, hmm, let's say decorator syntax.  <wink>  And suppose that
| each person is allowed three distinct votes, ranked in order, with the
| first vote getting 3 points, the second 2, and the third 1.  We might
| store the votes in a database, whose rows would naturally be tuples
| like
|
|   ('J2', 'C64', 'X11')
|
| Now suppose we want to calculate the total number of points for
| proposal X, but don't need to compute the totals for the other
| choices.  Code like the following would be a pretty natural
| approach:
|
|     for row in rows:
|         try:
|             points += 3-row.index(X)
|         except:
|             pass
|
| I realize that there are different ways to code it, but most
| are simply reimplementations of the proposed index function.

The algorithm is fine, it's the choice of sequence that's debatable.
Once you get index() for this application, next you'll want append().
After all, there's no apparent reason that at any time there must be
exactly 3 votes, so what if you want to collect data in several passes -

   for person, vote in data:
       try:
           row = votes[person]
       except KeyError:
           row = []
           votes[person] = row
       if len(row) < 3:
           row.append(vote)

Your application is really suited for a list or dictionary.  It can,
conceptually, support mutations like insert, delete and append, with
fairly obvious semantics in terms of your application.  I mean, if
you delete the first item, then the second item becomes the 3 point
vote, etc.  (In an application where that's not the case, then you
probably want a dictionary, where deleting whatever item has no
effect on the others.)  Compare with the mtime tuple returned by
time.localtime() - minus the first item, about the most you can say
is it's an mtime minus its first item.

No one is saying you must use a list then.  Do whatever you want!
But no one is forcing you to use a tuple, either (in this hypothetical
application), and if you need an index function, you know where to get it.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list