Search code examples
pythonif-statementlist-comprehension

Using list comprehension as condition for if else statement


I have the following code which works well

list = ["age", "test=53345", "anotherentry", "abc"]

val = [s for s in list if "test" in s]
if val != " ":
    print(val)

But what I'm trying to do is using the list comprehension as condition for an if else statement as I need to proof more than one word for occurence. Knowing it will not work, I'm searching for something like this:

PSEUDOCODE
if (is True = [s for s in list if "test" in s])
print(s)
elif (is True = [l for l in list if "anotherentry" in l])
print(l)
else:
print("None of the searched words found")

Solution

  • First of all, avoid using reserved words like "list", to name variables. (Reserved words are always branded as blue).

    If you need something like this:

    mylist = ["age", "test=53345", "anotherentry", "abc"]
    keywords = ["test", "anotherentry", "zzzz"]
        
        for el in mylist:
            for word in words:
                if (word in el):
                    print(el)
    

    Use this:

    [el for word in keywords for el in mylist if (word in el)]