Home > Back-end >  Python check if listelement is in value but return the listelement it found instead of true
Python check if listelement is in value but return the listelement it found instead of true

Time:09-25

mylist = ['dog','cat','bird']

var = "*ç%&dog*ç%"

a = any(mylist for mylist in var)
print(a)

This returns true, but i wan't it to return "dog" as a string. How can i do that?

CodePudding user response:

any() returns True if at least one of the elements in your list is True.

In your case, you better use list comprehension with condition:

a  = [x for x in mylist if x in var]
print(a)

Or you can use filter:

a = list(filter(lambda x: x in var, mylist))
print(a)

CodePudding user response:

Consider using a function to handle checking the word contained in the string, and return that word back if it exists.

def fn(word, var):
    if word in var:
        return word
    else:
        return None


for element in mylist:
    print(fn(element, var))
  • Related