Reputation: 23
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()
Upvotes: 2
Views: 79
Reputation: 34146
...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)
Upvotes: 5
Reputation: 32189
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.
Upvotes: 3