Search code examples
pythonsublist

how to check if a substring exist in the list having several sublists?


Let's say I have a list such as:

example_of_list = [[['aaaa'],['bbbb'],['cccc']], [['aabsd'],['fdwewd'],['dsfss']], [['sssss'],['ddddd'],['fffff']]]

And I want to check if my_list contains a substring

sub_sting = 'aaa'

So, In that case, this will give 'True' because I have 'aaaa' on the list as a sublist.

How to check this thing?

I already considered 'in' or 'str.contains', but it seems it doesn't give a proper response.


Solution

  • Here is a possible solution:

    from itertools import chain
    
    def contains(lst, substr):
        return any(substr in s for s in chain(*chain(*lst)))
    

    You can use the function in this way:

    lst = [[['aaaa'], ['bbbb'], ['cccc']],
           [['aabsd'], ['fdwewd'], ['dsfss']],
           [['sssss'], ['ddddd'], ['fffff']]]
    substr = "aaa"
    
    print(contains(lst, substr)) # True