tuples, index method, Python's design

Paul Boddie paul at boddie.org.uk
Tue Apr 10 12:14:20 EDT 2007


On 10 Apr, 17:44, Carsten Haese <cars... at uniqsys.com> wrote:
>
> You have a point. Here is my revised solution:
>
> assert current_player in p
> opponents = tuple(x for x in p if x is not current_player)
>
> The added advantage is that AssertionError is better than IndexError for
> conveying that a severe program bug has occurred.

Unless you're running python with the -O flag. So, instead of the
"unpythonic"...

i = p.index(current_player)
opponents = p[:i] + p[i+1:]

...we now have...

if current_player not in p:
    raise ValueError, current_player
opponents = tuple(x for x in p if x is not current_player)

Sure, p would probably be a list for a lot of games, and as I've noted
previously, since you have to specify all of the elements at once to
initialise the tuple, you should know where the player is. But this
only applies to situations where you have control over the code
needing to know the index *and* the code making the tuple in the first
place.

Paul




More information about the Python-list mailing list