[Tutor] RE: Newbie list question

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 13 Jul 2001 11:23:11 -0700 (PDT)


On Fri, 13 Jul 2001, Tobin, Mark wrote:

> Does:
> 
> foo += 'c'
> 
> act like an append then?  I always assumed it was the same as:

Not exactly like an append(), but very close: it's more like an extend().

###
>>> foo = ['austin', 'powers']
>>> foo += ['international', 'man', 'of', 'mystery']
>>> foo
['austin', 'powers', 'international', 'man', 'of', 'mystery']
###

If we forget the braces though, you're right: we'll hit a TypeError:

###
>>> foo = ['Mononoke']
>>> foo += 'Hime'
>>> foo
['Mononoke', 'H', 'i', 'm', 'e']
###

... or not!  Wow!  I completely forgot that strings can be treated like
lists of characters.  That was a surprise.  *grin*


The TypeError SHOULD happen here:

###
>>> foo = [1, 2, 3]
>>> foo += 4
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: argument to += must be a sequence
###

That's better.



If we had:

    letters = ['a' ,'b', 'c']

then to add the letter 'd' to the end of 'letters', we can do these:

    letters += ['c']
    letters = letters + ['c']
    letters.append('c')

All of these seem to have the same result in assigning 'letters', but they
do go about it in different ways.  For example,

    letters = letters + ['c']

creates a temporary list that contains the value of "letters + ['c']", and
finally assigns 'letters' to this intermediate value.

On the other hand, letters.append() directly influences the contents of
the list.  Here are three examples that shows that there's a real
difference in the methods:


###  test of foo = foo + bar
>>> x = ['eta', 'kappa']
>>> y = x
>>> x = x + ['nu']
>>> x
['eta', 'kappa', 'nu']
>>> y
['eta', 'kappa']
###


###  test of foo += bar
>>> x = ['eta', 'kappa']      
>>> y = x
>>> x += ['nu']
>>> x
['eta', 'kappa', 'nu']
>>> y
['eta', 'kappa', 'nu']
###

[Note: this example shows that x += y is NOT the same as x = x + y when we
deal with lists.  Be careful!]


###  test of foo.append(bar)
>>> x = ['eta', 'kappa']
>>> y = x
>>> x.append('nu')
>>> x
['eta', 'kappa', 'nu']
>>> y
['eta', 'kappa', 'nu']
###


Good luck to you.