Educative

Need explanation for the following

I dint quite understand the construct below,

if [i for i in line if “SOME TERM” in i]:
# do something

Let’s break this down into three parts:

The first i indicates that we want to add i as it is from the original list to our new list. We could also have written an expression such as i * 2, in which case the double of i’s value would have been added to the list.

The second part is the simple for loop in which i traverses the list.

The third part is a condition in terms of i. We will only add i to the new list if it fulfils this condition. An example could be i > 10, in which case all values greater than 10 would be added to the list.

In this way, list comprehension acts as a filter.

Thank You.