asdasdasd
asdasdasd

Reputation: 231

Python List operations

This is code I have, but it looks like non-python.

def __contains__(self, childName):
    """Determines if item is a child of this item"""
    for c in self.children:
        if c.name == childName:
            return True
    return False

What is the most "python" way of doing this? Use a lambda filter function? For some reason very few examples online actually work with a list of objects where you compare properties, they always show how to do this using a list of actual strings, but that's not very realistic.

Upvotes: 5

Views: 604

Answers (3)

Ned Batchelder
Ned Batchelder

Reputation: 375594

I would use:

return any(childName == c.name for c in self.children)

This is short, and has the same advantage as your code, that it will stop when it finds the first match.

If you'll be doing this often, and speed is a concern, you can create a new attribute which is the set of child names, and then just use return childName in self.childNames, but then you have to update the methods that change children to keep childNames current.

Upvotes: 7

Karoly Horvath
Karoly Horvath

Reputation: 96266

one way to do it with lambda:

from itertools import imap
return any(imap(lambda c: c.name == childName, self.children))

but the original solution seems clearer to me.

Upvotes: 1

Gabriel Ross
Gabriel Ross

Reputation: 5198

I would do this:

return childName in [c.name for c in self.children]

Upvotes: 5

Related Questions