Ad

How Can I Access Objects From Nested Lists With A Loop

- 1 answer

When looping through a nested list of objects with the standard for loop method I am receiving error AttributeError: 'list' object has no attribute 'val'

I'm looking for a way to return these values from the nested objects

class Class:
    def __init__(self,val,var_1 = True,var_2 = False,var_3 = True):
        self.val = val
        self.var_1 = var_1
        self.var_2 = var_2
        self.var_3 = var_3

    def print_num(self):
        return self.val


block = [[Class("O") for x in range(10)] for y in range(10)]

print(block[0][0].val) # this works returns "O" or correct var bool value

for x in block:        #This doesn't work 
    print(x.val)

['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']

Looking for this return, or similar

Ad

Answer

the problem is in your for loop.

You're using and iterator on block that is a list of lists. Then, by doing x.val you are trying to access the val attribute of lists, attribute that does not exist.

Try iterating one more time on x like for y in x.

Ad
source: stackoverflow.com
Ad