tuples, index method, Python's design

Terry Reedy tjreedy at udel.edu
Thu Apr 12 22:00:44 CEST 2007

"Alan Isaac" <aisaac at american.edu> wrote in message 
news:HNuTh.2516$ok6.3 at trnddc07...
| I doubt that *anyone* who programs in Python
| has not encountered the situation where they change
| a tuple to a list *solely* for the purpose of getting
| access to the index method. This suggests a missing
| method, does it not?  Who has not done this?
| Name yourself!

Me.  Not that I can remember, anyway.
But perhaps I have just not done enough of the right sort of programming.

| There is simply no conflict between the index method and immutability,
| but at the moment one is forced to choose.  Why?  Nobody has
| offered a real explanation of this.

Where 'real' == 'one you accept as valid'.

| I offered a simple use case.  Consider a game,
| where the *fixed* set p of players have a *fixed* order.

So the natural internal identifiers of the players are 0, ..., p-1 or, if 
you prefer and are willing to waste a tiny bit of space, 1, ..., p.  If you 
only access players via a sequential collection object, then you will 
access them by id.  If you pass around player instances separate from their 
container, than give them an id attribute.

I take it that in your game, no player, human or ai, ever gets eliminated 
or leaves or has a connection drop.

| A tuple is natural.

That is partly what is under debate.  Certainly you do not need a tuple for 
indexing a dict.

| Now for a player you want to construct the opponents.

Generator approach:
opponents = (op for op in players if op != player)

To do it once for everyone:
for player in players:
   player.opponents = tuple(op for op in players if op != player)

| If I had the index i it wd be p[:i]+p[i+1:], but how to get the index?

You either use the index to get the player or get it from the player (see 

opponents = p*[0]
for i in range(p):
  opponents[i] = players[:i] + players[i+1:]
opponents = tuple(opponents) # if you really care

for player in players:
  i = player.id
  player.opponents = players[:i] + players[i+1:]

It would never occur to me to get a player id by the O(n) scanning process.

| Other use cases have also been offered on this thread.
| What is the basic response?  "Do not worry about the
| loss of immutability, just use a list."  What kind of a
| response is that??  This sounds to me like "I do not
| really see the point of immutability", which is no
| response at all.

The main point of immutability is hashability by value (rather than by id).

Terry Jan Reedy

More information about the Python-list mailing list