Search code examples
pythonoopobjectmatrix

Creating a matrix of objects in python


I need to make a matrix of objects in python. I have found other solutions in various languages however cannot find a reliable and efficient method to do this in python.

Given the class

class Cell():
    def __init__(self):
        self.value = none 
        self.attribute1 = False
        self.attribute2 = False

I want to make a matrix of multiple 'cells' as efficiently as possible. Since the size of the matrix will be larger than 20 by 20, an iterative method would be useful. Any contributions are helpful


Solution

  • Update for correctness

    The numpy.full answer will copy the single existing Cell(), giving your references to one object. Use a list comprehension here:

    row = [[Cell() for _ in range(num_cols)] for _ in range(num_rows)]
    

    Old answer

    If you already have defined your objects, list comprehensions can help here:

    num_rows = 5
    num_cols = 6
    
    row = [Cell() for i in range(num_cols)]
    # The original way doesn't behave exactly right, this avoids 
    # deep nesting of the array. Also adding list(row) to create
    # a new object rather than carrying references to row to all rows
    mat = [list(row) for i in range(num_rows)]
    
    #[[Cell(), Cell(), Cell()...], [...], ..., [Cell(), ..., Cell()]]
    

    You can wrap them in numpy.array if you want to as well

    NumPy array full

    You could also use the numPy full method which is built-in and generates an n by m numpy array filled with your values:

    mat = numpy.full((num_rows, num_cols), Cell())
    

    The documentation can be found here