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.
5 List Operations in Python.
List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0. (See the official python.org list docs.) Assignment with an = on lists does not make a copy.
A list is an ordered and mutable Python container, being one of the most common data structures in Python. To create a list, the elements are placed inside square brackets ([]), separated by commas. As shown above, lists can contain elements of different types as well as duplicated elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With