0

I am trying to iterate over each number (and print it) that is associated with an object when it is initialized but only first element is returned and not the others. But this should work for normal for loop right?

   class Test():
        def __init__(self):
            self.data = [1,2,3,4,5,6,7,8]
        def listelements(self):
            for i in self.data:
              return [i]


    a = Test()
    print(a.listelements())
shaik moeed
  • 5,300
  • 1
  • 18
  • 54
IronMaiden
  • 552
  • 4
  • 20

2 Answers2

1

Try using yield instead of return as given below,

>>> class Test():
        def __init__(self):
            self.data = [1,2,3,4,5,6,7,8]
        def listelements(self):
            for i in self.data:
              yield [i]


>>> a = Test()
>>> print(a.listelements()) # you can iterate through this generator
<generator object Test.listelements at 0x00000220E0D03E08>

Output:

>>> for element in a.listelements():
        print(element)  
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
shaik moeed
  • 5,300
  • 1
  • 18
  • 54
1

No, return will break the for loop but yield won't. Please see the usage of python generator here

class Test():
    def __init__(self):
        self.data = [1, 2, 3, 4, 5, 6, 7, 8]

    def listelements(self):
        for i in self.data:
            yield i


a = Test()
print(list(a.listelements())) # [1, 2, 3, 4, 5, 6, 7, 8]
Matt Wang
  • 318
  • 1
  • 10