Filtering retains elements that satisfy a condition and excludes the rest. In Python, list comprehensions combine filtering with transformation, while filter applies a predicate without changing retained elements. section 7.5
Choose the form that matches the job:
- Use a comprehension when you want to transform selected values, such as squaring only even numbers. section 7.5
- Use filter when a function should decide which original elements remain, such as keeping words longer than four characters. section 7.5
- Filtering can ignore invalid input before aggregation, such as excluding strings containing nondigits before summing integers. section 7.6
Filtering while converting input
Given `10 abc 20 de44 30 55fg 40`, retain only strings that can become integers, convert them, and sum the results to produce 100. section 7.6
[x*x #1 for x in range(10) #2 if x%2 == 0] #3
Read the comprehension in three parts: expression, iteration, and the condition that filters the output. section 7.5
































