0

I want to make a list comprehension that stores a specific attribute of several objects and prints them to the screen.

This is what I tried:

class TextBox(object):
    def __init__(self, text=""):
        self.text = text

// imagine there are several TextBox objects in this list
textContainer = []

print([i.text for i.text in textContainer])

However, this throws NameError: name 'i' is not defined. Is it possible for me to print all of the text attributes without having to do a for loop like this?

for i in textContainer:
    print(i.text)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
FirTreeMan
  • 11
  • 1
  • 4
  • 1
    Why did you do: `for i.text in textContainer`? Is that normally how you write a for-clause? Pretend you were writing just a regular for loop... – juanpa.arrivillaga Nov 04 '22 at 17:38
  • @juanpa.arrivillaga regular for loops don't have the variable written before the for statement either :p – FirTreeMan Nov 04 '22 at 17:43
  • in the `for` loop you `for i`. In the list comprehension you have logic wise `text for text in container`. But you don't mention text of what i.e. the `i` in the llist comprehension. So what you want to do logic point: `text for object in container`. – Sid Nov 04 '22 at 17:43
  • @FirTreeMan So, you see **nothing strange about that?** – juanpa.arrivillaga Nov 04 '22 at 17:46

1 Answers1

0

The error is because you didn't write the list comprehension correctly. You should set a variable, e.g., i, as the representative of the elements of the list through which you're iterating, and use it to get the attribute you want, e.g., i.text:

print([i.text for i in textContainer])
msamsami
  • 644
  • 5
  • 10
  • [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – ray Nov 06 '22 at 01:57