Checking for items in sublists Today I'll demonstrate a simple function that searches for a item in all sublists of a list. For this it uses iteration, and keep in mind that it can be slow because of this. How can I improve it? Linked lists?

I doubt __contain__ can do the same.

def ListContainWSublist(searchfor, *args):

    Result = False

    for x in args:
        if type(x) == list:
            Result = ListContainWSublist(searchfor, *x)

        if x == searchfor:
            Result = True

    return Result
Proper type checking

To start off, you shouldn't be type checking like this:


if type(x) == list:
    ...



The proper way to go is to use Python's isinstance(a, b) function, where a is a value, and b is the type you're checking against. The portion of your code that involves type checking would be re-written like this:

if isinstance(x, list):
    ...


The difference here is that isinstance allows for inheritance when checking the type of a value, rather than simply checking the type of the value itself, which can be rather useful. If you're interested, you can read more about this at this Stackoverflow question.



Nitpicks

You should have the user pass a list of values, not pass a variable amount of arguments. Your function signature should look like this:

def list_contain_sublist(search_for, collection):
    ...


Your names are rather nasty, especially for Python. In Python, variable and function names should be in snake_case, and classes should be in PascalCase. Not the other way around.

There's also no need for the Result variable. You can change this line:


Result = ListContainWSublist(searchfor, *x)



To this:

return ListContainWSublist(searchfor, *x)


This line:


Result = True



Should become:

return True


And then this line:

Result = False


Can be removed all-together.



Other than those things, it looks fine. There may be a way to do this without recursion, but I'm not sure how to. I'll leave that up to you to figure out.