v.append(a)
adds a reference to r
's sublists to v
. r
and v
are different, but their contained items are the same. Expand your prints to include the sublists and you'll see
r = v = list()
r = [[2,2,1],[2,8,3],[10,2,1],[8,4,2],[4,6,4]]
for c, a in enumerate(r):
if len(v) > 0:
v[0][0]=c
v[0][1]=c
v.append(a)
print('r',r)
print('v',v)
print(hex(id(r)),[hex(id(i)) for i in r])
print(hex(id(v)),[hex(id(i)) for i in v])
I get
r [[4, 4, 1], [2, 8, 3], [10, 2, 1], [8, 4, 2], [4, 6, 4]]
v [[4, 4, 1], [2, 8, 3], [10, 2, 1], [8, 4, 2], [4, 6, 4]]
0x7f7f0d4e8848 ['0x7f7f0d55ff88', '0x7f7f0d55ffc8', '0x7f7f0d38c708', '0x7f7f0d38c648', '0x7f7f0d3a0ac8']
0x7f7f0d3a0c48 ['0x7f7f0d55ff88', '0x7f7f0d55ffc8', '0x7f7f0d38c708', '0x7f7f0d38c648', '0x7f7f0d3a0ac8']
If you want the lists to be independent, copy the sublists. All I did was change v.append(...)
(and removed the initial assignment to r
which was unneeded)
v = list()
r = [[2,2,1],[2,8,3],[10,2,1],[8,4,2],[4,6,4]]
for c, a in enumerate(r):
if len(v) > 0:
v[0][0]=c
v[0][1]=c
v.append(a[:])
print('r',r)
print('v',v)
print(hex(id(r)),[hex(id(i)) for i in r])
print(hex(id(v)),[hex(id(i)) for i in v])
Which gives
r [[2, 2, 1], [2, 8, 3], [10, 2, 1], [8, 4, 2], [4, 6, 4]]
v [[4, 4, 1], [2, 8, 3], [10, 2, 1], [8, 4, 2], [4, 6, 4]]
0x7fa258a91848 ['0x7fa258b08f88', '0x7fa258b08fc8', '0x7fa258935748', '0x7fa258935688', '0x7fa258949b08']
0x7fa258949c88 ['0x7fa2589357c8', '0x7fa258a915c8', '0x7fa258949d08', '0x7fa258949d88', '0x7fa258949dc8']