Issue 9108: list object variable assign with multiplication sign (original) (raw)

platform: ubuntu 10.04 amd64, python 2.6.5 r265:79063

run below code

a = [{}, {}, {}] b = [{}] + [{}] + [{}] c = [{}] * 3 print a, len(a), type(a) print b, len(b), type(b) print c, len(c), type(c) a[1]["test"] = 1234 b[1]["test"] = 1234 c[1]["test"] = 1234 print a print b print c

the output is

[{}, {}, {}] 3 <type 'list'> [{}, {}, {}] 3 <type 'list'> [{}, {}, {}] 3 <type 'list'> [{}, {'test': 1234}, {}] [{}, {'test': 1234}, {}] [{'test': 1234}, {'test': 1234}, {'test': 1234}]

each dict key in variable c seen to assign with the same value.

That's because with [{}] * 3 you get a list with 3 copies of the same object, so all the elements in c refer to the same dict:

a = [{}, {}, {}] b = [{}] + [{}] + [{}] c = [{}] * 3 map(id, a) [12850496, 12850784, 12850928] map(id, b) [12851648, 12851072, 12851792] map(id, c) [12852080, 12852080, 12852080]