Search code examples
pythonpython-3.xfunctional-programming

How to return list of strings if a string in a list contains another string python


If i have a list of strings, I want to return the strings in that list that are contained in the strings of that list. For instance: ["red", "blue", "loss", "boss", "sloss"] would return ["loss"]. I have been trying to do this only using lambdas + filter and no loops/comprehensions but can't seem to figure out why my solution isnt working:

list(filter(lambda x: x if x in stringlist else "", stringlist))

Solution

  • You are checking if the strings are in the lsit of string, not if the strings are substrings of one of the strings.

    Try:

    list(filter(lambda x: any(x in y and x != y for y in stringlist), stringlist))
    

    It checks if the strings are stricly contained in one of the other string ( x in y and x != y ) so it will not match equal strings in the list.