List behaviour

bockman at virgilio.it bockman at virgilio.it
Thu May 15 06:41:31 EDT 2008


On 15 Mag, 12:08, Gabriel <g... 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.
>
> Regards
>
> Gabriel

The reason is that
    tasks = [[]]*6
creates a list with six elements pointing to *the same* list, so when
you change one,
it shows six times.

In other words, your code is equivalent to this:
>>> a = []
>>> tasks = [a,a,a,a,a,a]
>>> a.append(1)
>>> tasks
[[1], [1], [1], [1], [1], [1]]


Insead, to create a list of lists, use the list comprehension:

>>> tasks = [ [] for x in xrange(6) ]
>>> tasks[0].append(1)
>>> tasks
[[1], [], [], [], [], []]
>>>

Ciao
-----
FB



More information about the Python-list mailing list