Search code examples
pythonarrayslistadjacency-matrix

2D list filling a whole column


I want an algorithm that makes an adjacency matrix. The input is a 1D list and it outputs an 2D list with how the numbers changed. This is what I have:

n_clusters = 5
user = [4, 4, 4, 2, 3, 3, 0, 0, 0]  # input array

movement_counts = [[0] * n_clusters] * n_clusters  # row is from, col is to

prev_label = user[0]
for label in user[1:]:
    if label != prev_label:
        movement_counts[prev_label][label] += 1
    prev_label = label

This returns

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

But I want it to return this:

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

Why is it filling the whole column with numbers instead of just one element?


Solution

  • Replace:

    movement_counts = [[0] * n_clusters] * n_clusters
    

    with:

    movement_counts = [[0] * n_clusters for _ in range(n_clusters)]
    

    Because, movement_counts = [[0] * n_clusters] * n_clusters generates the list that contains sublists that point to same reference inside memory, so if you change any of element inside any of the sublist the change will occur in all the sublists.