[Solved] Convert a for loop to a list comprehension


As it is written, no you cannot directly write it as a list comprehension.

however, if you rewrite the computation of mat to be a single expression. (in this case, you would use any)

mylist = []
for x in list1:
    mat = any((x[:-14] in y) for y in list2)
    if not mat:
        mylist.append(x)

Then move that definition directly into the if not condition:

mylist = []
for x in list1:
    if not any((x[:-14] in y) for y in list2):
        mylist.append(x)

Now it is pretty straight forward to convert:

mylist = [x for x in list1 if not any((x[:-14] in y) for y in list2)]

2

solved Convert a for loop to a list comprehension