1

I am trying to create a 2d array in python using nested for loops. Here is my code:

count = 0
stateArray = []
state = [0]*2
for i in range (0,2):
    for j in range(0,2):
        state[0] = i
        state[1] = j
        stateArray.append(state)
        print (count)
        print (stateArray[count])
        count += 1
print(stateArray[0])
print(stateArray[1])
print(stateArray[2])

Here is my output:

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

Why does my stateArray change to storing the last iteration of the fo loop at every index once I've exited the loop?

  • 1
    You keep modifying appending the same *list* to your outer list: `stateArray.append(state)` why do you expect it to have different values? It is *the same list* So the obvious solution is to simply use *a new list*, `state = []` *inside* your outer loop, or `.append` *copies* of `state` to `stateArray` – juanpa.arrivillaga Nov 16 '18 at 05:22

1 Answers1

0

I think you need:

count = 0
stateArray = []
# state = [0]*2
for i in range (0,2):
    for j in range(0,2):
        # state[0] = i
        # state[1] = j
        stateArray.append([i,j])
        print (count)
        print (stateArray[count])
        count += 1
print(stateArray[0])
print(stateArray[1])
print(stateArray[2])

Output:

0
[0, 0]
1
[0, 1]
2
[1, 0]
3
[1, 1]
[0, 0]
[0, 1]
[1, 0]
Sociopath
  • 13,068
  • 19
  • 47
  • 75