2

I have simple class like this

class MyClass():
    def test(self):
      print "Calling Test"

Then i create a list:

lobj=[MyClass() for i in range (100)]

Now I want to iterate each object in lobj and invoke its medthod test(). I know i can use for loop. However, i wonder if there is any other way (just to avoid the for loop when the list is relatively large)? For example

lobj[:].test()
2
  • Do you want to capture the result of that test function? Commented May 21, 2014 at 6:40
  • 1
    Why does the size of the list matter for whether or not you use a for loop? Any thing that calls a method on each object is going to do exactly the same thing. Commented May 21, 2014 at 6:42

2 Answers 2

5

...I wonder if there is any other way (just to avoid the for loop when the list is relatively large)?

Yes. You can use the built-in function map() and a lambda function. If you want to just call the method on each element, do:

map(lambda x:x.test(), lobj)

And if you want to store the results in a list:

v = map(lambda x:x.test(), lobj)
Sign up to request clarification or add additional context in comments.

Comments

3

The best you can do is:

[i.test() for i in lobj]

This calls the method but then doesn't store the result anywhere so the list gets discarded after it is done calling the method for all the instances.

1 Comment

Thanks. I can be done in this way too. I would like to up vote your answer but I don't have enough rep.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.