Newbie Question, list = list + x VS append (x)

Terry Reedy tjreedy at udel.edu
Fri Nov 29 15:33:58 EST 2002


Seq + seq (of same type) is sequence concatenation: len(r+s) =
len(r)+len(s)

>>> 'a'+'b'
'ab'
>>> (1,)+(2,)
(1, 2)
>>> [1]+[2]
[1, 2]
>>> (1,)+[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can only concatenate tuple (not "list") to tuple

While not commutative, seq + is associative with identity (empty seq
of type) and is thus a reduction operator.  Ie, reduce(tuple.__add__,
tuples, ()) => tuple, etc

list.append(object), specific to lists, simply tacks object on to the
end of list.
It never looks at the type of object.  If it is a list, that is
irrelevant.

list.extend(seq) is similar to list+seq but is more general.

Terry J. Reedy






More information about the Python-list mailing list