Creating a matrix of objects in python

1103 views 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. Any contributions are useful.

answered question

A matrix like a x*y array?

@Guimoute Yes. Like a two dimensional array

2 Answers


Maybe just using nested lists?

Something like:

mtx = [[0, 1, 2], [3, 4, 5]]
mtx[1][1] # 4

posted this

If you know in advance what size your matrix is you could initialize a numpy array using np.empty or np.zeros and then fill in the cells using indexing.

Or you could append items to lists and then convert to an array by np.array(list). You'll want your matrix as a numpy array for any calculations you do.

posted this

Have an answer?


Please login first before posting an answer.