FW: Newbie list question

Skip Montanaro skip at pobox.com
Fri Jul 13 13:53:34 EDT 2001


    Mark> Does:

    Mark> foo += 'c'

    Mark> act like an append then?  I always assumed it was the same as:

    Mark> foo = foo + 'c'

    Mark> which obviously should raise a TypeError.  Here however it works,
    Mark> in that it appends 'c' to the object to which foo refers and thus
    Mark> to the object to which bar refers...

You can tell whether a variable name has been bound to a new object or not
by calling the id builtin function:

    >>> foo = [1,2,3]
    >>> id(foo)
    136434132
    >>> foo += '4'
    >>> id(foo)
    136434132
    >>> foo += '567'
    >>> id(foo)
    136434132
    >>> foo
    [1, 2, 3, '4', '5', '6', '7']
    >>> foo += u"987"
    >>> foo
    [1, 2, 3, '4', '5', '6', '7', u'9', u'8', u'7']
    >>> id(foo)
    136434132

That you can augment a list with a string may seem weird until you realize
that Python considers lists, tuples, plain strings, and Unicode strings to
all be sequences, hence the acceptability of augmenting a list with strings.

-- 
Skip Montanaro (skip at pobox.com)
(847)971-7098




More information about the Python-list mailing list