Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make each method in Python?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading