0

So, I was returning to python from C and had forgotten how to make 2D Arrays in python. So, I came up with this quick and dirty trick of appending a list over and over again into an empty list with a for loop. However, when I try to update a single element, the entire column gets updated

l=[]
pp=[]
for i in range(5):
    pp.append(0)
for i in range(5):
    l.append(pp)
l[0][2]=5
for i in l:
    print(i)

The output I expect:

[0, 0, 5, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

The output I get:

[0, 0, 5, 0, 0]
[0, 0, 5, 0, 0]
[0, 0, 5, 0, 0]
[0, 0, 5, 0, 0]
[0, 0, 5, 0, 0]
  • 1
    Also if your intention is to eventually do linear algebra I would recommend using `numpy` which case you would just do `l = np.zeros((5,5))` – Cory Kramer Sep 17 '21 at 18:47
  • each line points to `pp` so when you change any line, you change the single list `pp`. [link]https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it – Sean C Sep 17 '21 at 18:48

0 Answers0