Generating a random subsequence

Justin Sheehy justin at
Wed Jan 9 22:16:50 CET 2002

Tom Bryan <tbryan at> writes:

> Is that just true of +=? 
> That is, if returnSeq is a list then, I can say
> returnSeq = returnSeq + item
> OR
> returnSeq.append( item )
> OR
> returnSeq += item
> You're saying that the last one is roughly equivalent to the second one and 
> not the first?  Or are they all three equivalent?
> the-last-time-I-used-python-there-wasn't-a-+=-ly,  

The behavior of all of the augmented assignment operators depends on
the presence of a special method in the left operand.  If the special
method is not present, they are roughly equivalent to 'a = a OP b".

IMO, the definition of those methods for some of the builtin data
structures (e.g. lists) were poorly chosen.

note: It is not the behavior of the operator that I take issue with.
      It is the behavior of the method exposed to that operator by
      certain datatypes.

A trivial example that illustrates how the definitions of these
methods causes Python to badly violate the principle of least surprise
when used by someone who knew Python pre-augassign and now knows that
a "+=" operator exists:

def augassign(seq1, seq2):
    seq1 += seq2
    return seq1

>>> rhs = (4,)
>>> a = (1, 2, 3)
>>> b = [1, 2, 3]
>>> augassign(a, rhs)
(1, 2, 3, 4)
>>> a
(1, 2, 3)
>>> augassign(b, rhs)
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]

Many assumptions that I am used to with Python are not valid with
regard to that last line.  If I had not been explicitly educated about
the behavior of += and friends, I would definitely not expect the
sequence referred to by a or b here to (maybe) be mutated by the
function call.

I believe that giving lists this behavior was a serious mistake.
Using this new behavior makes sense for user-defined classes and some
interesting data structures such as matrices, but this disparity in
results between the basic sequence types is very unfortunate.

This may gain some efficiency in reducing the number of list
allocation, but I don't think that the confusion is worth it.

A small implementation detail, a real step away from Programming for Everybody.



More information about the Python-list mailing list