Michi
Michi

Reputation: 125

How do I access an object's attribute while iterating through a nested list in Python?

I have an object defined as follows:

class word(object): #object class

    def __init__(self, originalWord=None, azWord=None, wLength=None):
        self.originalWord = originalWord
        self.azWord = azWord
        self.wLength = wLength

I have a list called results[], where each index x in the list contains another list of words objects of length x. E.g. in results[3] there is a list of objects of length 3 and one of those objects may be (dog, gdo, 3). I have a value called maxL that represents the length of the list results[]. How do I access (and then print) the attributes I want by iterating through results[] and all of its lists?

This is what I have thus far but I know the syntax is wrong:

for x in range(0,maxL):
    for y in results[x]:
        print(results[x][y].azWord)

Upvotes: 2

Views: 539

Answers (2)

Christian Tapia
Christian Tapia

Reputation: 34146

In the first loop:

for x in range(0,maxL):

you are looping through indices. In the second:

for y in results[x]:

you are looping through elements. In this case, through elements of a list. So you can access the attribute like:

print(y.azWord)
# ...

Note:

  • I would recommend you to follow Python naming conventions. Name your class as Word.

  • I would also recommend you to use more representative names, like:

    for i in range(0, maxL):
        for element in results[i]:
            print(element.azWord)
    
  • You can also loop through elements in the first loop. You should do this unless you want to modify the elements or you need to use indices:

    for words_list in results:
        for word in words_list:
            print(word.azWord)
    

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

Why don't you just iterate the list like so:

for row in results:
    for item in row:
        print(item.azWord)

Because in your example results[x][y] would be incorrect. y is an object, not an int so you cannot use it to index from results. I would just use the above code to pull the objects themselves.

Or to use something closer to your original code

for x in range(0,maxL):
    for y in results[x]:
        print(y.azWord) # note y is the object itself, not an index

Upvotes: 2

Related Questions