Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 787
asdasdasd Avatar asked Aug 18 '11 23:08

asdasdasd


People also ask

How many list operations are there in Python?

5 List Operations in Python.

How does list () work 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.

What does list [:] mean in Python?

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.


1 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.

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.

like image 182
Ned Batchelder Avatar answered Oct 09 '22 04:10

Ned Batchelder