1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You forgot a nested for:

for x in block:
    for y in x:
        print(y.val)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.