List behaviour

Diez B. Roggisch deets at nospam.web.de
Thu May 15 06:37:04 EDT 2008


Gabriel 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.

The "problem" is that all the lists inside the outer list are the same
list - you can check that with 

id(tasks[0]) == id(tasks[1])

So instead of creating a list of list by the *-operator that only multiplies
the references (which is fine immutable objects like strings or numbers),
you need to explicitly create new lists, e.g. with a list-comprehension:

tasks = [[] for _ in xrange(6)]

Try this and everything will work as expected.

Diez



More information about the Python-list mailing list