gho gho - 7 months ago 15
Python Question

list comprehension error

Can someone help me to correct this list comprehension:

line_list = [line for line in file.splitlines() if item in line for item in my_list]


Because I get the following error

UnboundLocalError: local variable 'item' referenced before assignment

Answer

You have it a bit scrambled:

line_list = [line for line in file.splitlines() for item in my_list if item in line]

The filter goes at the end.

Also note that the above might put multiple duplicate lines in a row if there is more than one match in my_list. The following will check if there are any matches, then add the line only once:

line_list = [line for line in file.splitlines() if any(item in line for item in my_list)]