0

I have created a 2D array in Python as:

dp = [[0] * 3] * 4

When I modify a certain element in it, each column of the array gets modified:

dp[1][2] = 10
print(dp)
> [[0,0,10], [0,0,10], [0,0,10], [0,0,10]]

Why is that the case and how can I update only the correct element of the array?

Asmita Poddar
  • 524
  • 1
  • 11
  • 27

1 Answers1

2

Ah, you have stumbled onto what I thought was a very strange behavior of lists (turns out it makes sense).

basically what is happening is that each sublist is a copy of the previous, and they all point at the same object, meaning that modifying one modifies all of them.

When working with arrays I suggest using numpy

import numpy as np
dp = np.zeros((4,3))
Ftagliacarne
  • 675
  • 8
  • 16