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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to