Skip to content
Advertisement

How do i fill a list with zeros? When I try to .append(0), I am met with an error message saying that ‘int’ object has no attribute ‘add’

class Matrix(object):
    def __init__(self,num_rows=2,num_cols=2):
        '''
            WRITE DOCSTRING HERE!
        '''
        if num_rows <= 0:
            raise ValueError("Matrix: Error, the dimensions must be positive integers!")
        if num_cols <= 0:
            raise ValueError("Matrix: Error, the dimensions must be positive integers!")
        self.x = num_rows
        self.y = num_cols
        self.z = []
        for i in range(self.x):
            self.z.append([])
        for i in self.z:
            for i in range(len(self.z)):
                i.add(0)
        return self.z
Traceback (most recent call last):
  python_unit_test line 10, in test_unit
    A = Matrix()
  File "proj11.py", line 32, in __init__
    i.add(0)
AttributeError: 'int' object has no attribute 'add'

Advertisement

Answer

i is defined twice in your nested loop, the 2nd i will overwrite the first. Rename one of them to avoid this. Also, .add should be .append and range(len(self.z)) should probably be range(self.y) in order to have the correct number of columns.

for row in self.z:
    for _ in range(self.y):
        row.append(0)

Side note: why is __init__ returning a value?

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement