Python List Operations

This is the code I have, but it looks like a 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 to do this? Use lambda filter function? For some reason, very few online examples really work with a list of objects in which you compare properties, they always show how to do this using a list of real lines, but this is not very realistic.

+5
source share
3 answers

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.

, , , , return childName in self.childNames, , , childNames.

+7

:

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

one way to do this with lambda:

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

but the original solution seems clearer to me.

+1
source

All Articles