Search code examples
pythonlistlist-comprehension

Why can't I check if a string is a substring of each string in a list by using list comprehension?


I have the following code:

MFII_files = ['patrick', 'domccc', 'joseph', 'harry']

file_name = 'ccc'

if file_name in MFII_file for MFII_file in MFII_files: 
    print('yes')

But when I run it, it says invalid syntax pointing to the for. Why does this not work?


Solution

  • Use any to perform this check instead.

    if any(file_name in MFII_file for MFII_file in MFII_files):
    

    any takes an iterable and returns a result indicating whether any element of the iterable was true. In this case, we can conveniently pass a generator expression.