List behaviour

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu May 15 06:36:34 EDT 2008


Gabriel a écrit :
> 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], [], [], [], [], []]

The problem here is that your first statement

#>>> tasks = [[]]*6

creates a list (task) containing 6 references to the *same* (empty) list 
object. You can check this easily using the identity test operator 'is':

#>>> tasks[0] is tasks[1]
True


In fact, it's exactly as if you had written:

#>>> task = []
#>>> tasks = []
#>>> for i in range(6):
#...     tasks.append(task)
#...

If you want 6 different list objects in tasks, you can use a list 
comprehension instead:

#>>> tasks = [[] for i in range(6)]
#>>> tasks
[[], [], [], [], [], []]
#>>> tasks[0].append(1)
#>>> tasks
[[1], [], [], [], [], []]

HTH



More information about the Python-list mailing list