I want to create a nested array of 0s of m x n dimensions. I will be iterating through the array and assigning values later.
If I do this:
l = [[0] * 3] * 3
for i in range(3):
for j in range(3):
if i == 0:
l[i][j] = 1
My conditional doesn't seem to apply and every value is assigned to the list regardless of i. I know the problem is caused by copying the lists of 0s in the first line of code. So I took a slice of each inner list like this to fix it:
l = [[0] * 3] * 3
for i in range(3):
l[i] = l[i][:]
for j in range(3):
if i == 0:
l[i][j] = 1
This feels redundant and I'm wondering if there's a better way to initialize nested lists.