List listing

I am new to programming and I have this basic problem that I cannot fix. I simplified it as much as possible. In this simplified version, I repeat the empty list. I just want to keep the indices in a "symmetric matrix":

n = 2
B = [[None] * n] * n
print B, "\n"
for i in range(n):
    for j in range(n):
        B[i][j] = [i, j]
        print B

Initially, the list is as follows:

[[None, None], [None, None]] 

After the cyclic trough, I expect the printout to be as follows:

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

Instead, I get the following:

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

What am I missing? Thanks for helping ...

+4
source share
4 answers

What you need instead of the current method of determination Bis the n"fresh" instances of the sublist:

B = [[None] * n for _ in range(n)]

which is equivalent, but shorter and (for Pythonista) more readable than:

B = []
for _ in range(n):
    B.append([None] * n)

, Python - , ; . :

>>> a = []
>>> b = [a, a]  # list of 2 items, both pointing to the same list instance
>>> b[0].append(1)  # b[0] refers to the same list instance also referenced by a
>>> print b
[[1], [1]]

:

>>> b = [[], []]  # list of 2 distinct sublists
>>> b[0].append(1)
>>> print b
[[1], []]

B = [[None] * n] * n

: , n None; "" , n ; , , .

PS, Python - , , , , int float str .., - , , , , .

+3

:

n=2
B=[[None]*n]*n
for x in B:
     print id(x)

:

4534759576
4534759576
+3

, :

    n=2
    B = [[None for i in range(n)] for i in range(n)]
    print B, "\n"
    for i in range(n):
        for j in range(n):
        B[i][j] = [i, j]
        print B
+1

The key to understanding what is going on here is understanding that you are creating lists with shared links using the method [[None]*n]*n. Check out this visualization of what your code is doing; this should make things clearer. This blog post also explains how names and values ​​work in Python.

+1
source

All Articles