0

I have initialised an empty 2d array as follows:

matrixLength = (len(a)+1)*(len(b)+1)

matrix = []
    step = []

    for i in range(matrixLength):
        matrix.append(step)

when I print it, it gives me this:

[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

so far so good. But when I want to iterate over the first Len(a) elements of the 2d array, with the following code:

for i in range(0, len(a)+1):
        print(i)
        matrix[i].append(i)

print (matrix)

instead of getting an array with only the first len(a) elements filled, like this:

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

I get this instead:

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

why?

4
  • 1
    They are all the same list. Commented Mar 13, 2018 at 18:07
  • 2
    Possible duplicate of List of lists changes reflected across sublists unexpectedly Commented Mar 13, 2018 at 18:08
  • 1
    Though not exactly the same, but essentially is a dupe. Commented Mar 13, 2018 at 18:10
  • got it! cheers guys! Commented Mar 13, 2018 at 18:32

1 Answer 1

1

When you set step to [] you create a reference to one instance of the list type, so when you append matrix with step you put the same reference in all positions. You can easily verify this by printing all matrix element id:

for el in matrix:     
    print(id(el))

You need to create a different list for each element:

matrixLength = (len(a)+1)*(len(b)+1)                   
matrix = []
for i in range(matrixLength):     
     matrix.append(list())

Then you'll be able to update each list independently.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.