Search code examples
pythonpython-3.xdynamicadjacency-matrixadjacency-list

How to assign value to an element of 2d array with dynamic size?


I want to create an adjacency matrix for a graph without using any libraries. The problem is the size of the graph is not static and it increases over time. So I can not use a command like:

adj = [ [None for i in range(5)] for j in range(4) ]

and for example, assign 4 to element (1,1):

adj[1][1]=4

I have created an empty list called adj:

adj = []

now each time a node is added to the graph I add a list to adj:

adj.append([])

How can I assign a value to a specific element of the matrix, as I did with q[1][1]=4 when the size was fixed?


Solution

  • You can start with any default size and then use extend to add elements to a sublist, or add a new sublist.

    adj = [ [0 for i in range(2)] for j in range(2) ]
    print(adj)
    #[[0, 0], [0, 0]]
    adj[0].extend([1, 1])
    #[[0, 0, 1, 1], [0, 0]]
    print(adj)
    adj.extend([[0, 0, 0, 0, 0]])
    print(adj)
    #[[0, 0, 1, 1], [0, 0], [0, 0, 0, 0, 0]]
    

    Once you resize your list based on requirement, then you can assign your elements.

    adj[0][0] = 2
    adj[1][1] = 3
    adj[2][2] = 4
    print(adj)
    #[[2, 0, 1, 1], [0, 3], [0, 0, 4, 0, 0]]