1

I have an error on array substitution.

way=[[0]*4]*2
arri=[1]*4
for i in range(0,2):
    arri[i]=0
    way[i]=arri
    print(way)

I thought that

[[0, 1, 1, 1], [0, 0, 0, 0]]
[[0, 1, 1, 1], [0, 0, 1, 1]]

will be printed on the console, but actually:

[[0, 1, 1, 1], [0, 0, 0, 0]]
[[0, 0, 1, 1], [0, 0, 1, 1]]

This got printed on console.

When I fix way[i] to way[1],

[[0, 0, 0, 0], [0, 1, 1, 1]]
[[0, 0, 0, 0], [0, 0, 1, 1]]

This got printed.

What's the point I'm missing here?

1 Answer 1

1

Because way=[[0]*4]*2 gives you two references pointing to the same list [0, 0, 0, 0], which can be proved by their identical id:

In [4]: way=[[0]*4]*2
In [5]: way
Out[5]: [[0, 0, 0, 0], [0, 0, 0, 0]]
In [6]: way[0][0] = 1
In [7]: way
Out[7]: [[1, 0, 0, 0], [1, 0, 0, 0]]
In [8]: id(way[0])
Out[8]: 39479992
In [9]: id(way[1])
Out[9]: 39479992

You may use list comprehension to create your lists like way = [[0]*4 for i in range(2)]

You may ask why [0]*4 gives you a normal [0, 0, 0, 0]:

In [16]: way
Out[16]: [0, 0, 0, 0]
In [17]: way[0] = 1
In [18]: way
Out[18]: [1, 0, 0, 0]  # not [1, 1, 1, 1]

That's because 0 is an integer, which is of an immutable type int, and [0, 0, 0, 0] is of a mutable type list. You can see this link to get more information.

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.