0

i am trying to make a nested list using append function, but the last value will recover pervious values, anyone can tell me why, and how to do it correctly. thanks

d= []
temp = [0,0,0]
for i in range(4):
   temp[0] = i+1
   d.append(temp)

the output shows:

[[4, 0, 0], [4, 0, 0], [4, 0, 0], [4, 0, 0]]

but the output that i want is

[[1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]]

2 Answers2

1

Your resultant list is [temp, temp, temp, temp]. If you want the objects to be different, you'll have to make a new sub-list every time. One easy way, using a list comprehension, would be

d = [[i, 0, 0] for i in range(1, 5)]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • Alternatively, use the OP's code, and just change `d.append(temp)` to `d.append(temp[:])`, using the "empty slice" to insert a shallow copy of `temp` each time, not another alias to it. Your list comprehension is faster and clearer about what it's doing, shallow copying is just the minimal fix. – ShadowRanger Oct 26 '17 at 03:23
  • thank you very much for answering. – Randy Lang Oct 26 '17 at 03:45
0

Try this:

d= []
temp = [0,0,0]
for i in range(4):
   tmp = [t for t in temp]
   tmp[0] = i+1
   d.append(tmp)
Simon Mengong
  • 2,625
  • 10
  • 22