List behaviour

A.T.Hofkamp hat at se-162.se.wtb.tue.nl
Thu May 15 06:48:49 EDT 2008


On 2008-05-15, Gabriel <gabe at dragffy.com> wrote:
> Hi all
>
> Just wondering if someone could clarify this behaviour for me, please?
>
>>>> tasks = [[]]*6
>>>> tasks
> [[], [], [], [], [], []]
>>>> tasks[0].append(1)
>>>> tasks
> [[1], [1], [1], [1], [1], [1]]
>
> Well what I was expecting to end up with was something like:
> ?>>> tasks
> [[1], [], [], [], [], []]
>
>
> I got this example from page 38 of Beginning Python.

This is a more complicated case of

a = []
b = a

a.append(1)
print b  # Will print "[1]"

This is the case, because both a and b refer to the same list data-value.


In your case, basically what you are doing is

a = []          # a is an empty list (introduced for easier explanation)
tasks = [a]     # tasks is a list with 1 'a'
tasks = tasks*6 # you create 5 additional references to 'a' in 'tasks

ie tasks is now the equivalent of [a, a, a, a, a, a]. It refers to the same 'a'
list 6 times. When you print 'tasks', you actually print the same 'a' value 6
times.


in particular, tasks is **NOT**

a,b,c,d,e,f = [], [], [], [], [], []  # create 6 different empty list values
tasks2 = [a, b, c, d, e, f]

although when you print both tasks, you won't see the difference.


Next, 'tasks[0]' refers to the first list element, that is, value 'a'. To that
list you append an element. In other words, you do "a.append(1)".

However, since tasks has 6 references to the same list 'a', all its members
appear to be changed (but you are really displaying the same value 6 times).


You can query this equality with 'is':

print tasks[0] is tasks[1]  # will print 'True'
print tasks2[0] is tasks2[1]  # Will print 'False'


Sincerely,
Albert



More information about the Python-list mailing list