Sometimes, we don’t want to operate on each element of a collection, rather only on specific elements. Adding an if expression to the for generator allows us to filter out the elements we aren’t interested in.
Let’s look at an example where we start with an array of integers from 1 to 10. We want to create a new array of even integers using the initial array. How would we go about doing that?
In line 4, of the code above, we have added a condition to our generator: element % 2 == 0. The for expression will only iterate over the elements of the collection for which this condition is true, i.e., even numbers.