Trying to understand += better

Steve Howell showell30 at yahoo.com
Mon Nov 23 00:42:26 EST 2009


On Nov 22, 9:11 pm, n00m <n... at narod.ru> wrote:
> > The first statement is creating a whole new list;
>
> Yes but *imo* not quite exactly so.
> We can't think of 2 lists as of absolutely independent
> things.
> [...]

You are correct that two lists can both have the same mutable object
as items, and if you mutate that object, both lists will see that
mutation.  Changing the innards of an item doesn't change the list, if
you think of the list as just a collection of ids, but your point is
well taken.  It is probably easiest to understand all this with a more
elaborate example.

>>> mutable = {'foo': 'bar'}
>>> list1 = [mutable, 'bla']
>>> list2 = list1 + ['another element']
>>> list1
[{'foo': 'bar'}, 'bla']
>>> list2
[{'foo': 'bar'}, 'bla', 'another element']

So list2 and list1 are no longer the same list, but...

>>> mutable['foo'] = 'new value for mutable'
>>> list1
[{'foo': 'new value for mutable'}, 'bla']
>>> list2
[{'foo': 'new value for mutable'}, 'bla', 'another element']

They do still share a common element, as shown above.

But you can reassign the first element of list2 without affecting
list1:

>>> list2[0] = 'only list 2'
>>> list1
[{'foo': 'new value for mutable'}, 'bla']
>>> list2
['only list 2', 'bla', 'another element']

Now look at fred_list and barney_list below.  Since you use +=,
fred_list and barney_list stay tied together even when you *think* you
are only assigning a new value to barney_list[0].

>>> fred_list = [0]
>>> barney_list = fred_list
>>> barney_list += [1]
>>> barney_list
[0, 1]
>>> fred_list
[0, 1]
>>> barney_list[0] = 'barney'
>>> barney_list
['barney', 1]
>>> fred_list
['barney', 1]



More information about the Python-list mailing list