Home > other >  How to make each method in Python?
How to make each method in Python?

Time:12-26

How can I make method each in Python like its in Ruby? Is that possible, am really do!

In Ruby its looks like:

%w[1 2 3 4].each { |i| puts i}

In Python we have for:

for i in [1, 2, 3]: print(i)

So, I want to make each method in Python, here is my code:

class Iter:
    def each(self, data):
        processed = data.__iter__()
        yield processed.__next__()


if __name__ == "__main__":
    test = Iter()
    print(list(test.each([1, 2, 3])))

Its working not as each, its return only first element. Thx in advance!

CodePudding user response:

class Iter:
def each(self, data):
    yield from data

if __name__ == "__main__":
test = Iter()
for i in test.each([1, 2, 3]):
    print(I)

To implement the each method in python that is similar to Ruby, you can use the yield statement. If you use it inside a for it should work that way.

I'll also add the link to the documentation of yield statement here.

  • Related