Here are 5 ways to filter a Python list based on conditions:
1. Filter Numbers Greater Than a Threshold:
Filter numbers greater than 20:
numbers = [7, 25, 9, 30, 15] # Filter numbers greater than twenty filtered_result = [n for n in numbers if n > 20] print("Numbers greater than 20:", filtered_result)
The result:
Numbers greater than 20: [25, 30]
2. Filter Strings Containing a Specific Substring:
Filter words containing the substring ‘an‘:
words = ['apple', 'banana', 'orange', 'melon'] # Filter words containing the substring an filtered_result = [w for w in words if 'an' in w] print("Words containing 'an':", filtered_result)
The result:
Words containing 'an': ['banana', 'orange']
3. Filter Even Numbers:
Filter even numbers:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Filter even numbers filtered_result = [n for n in numbers if n % 2 == 0] print("Even Numbers:", filtered_result)
The result:
Even Numbers: [2, 4, 6, 8]
4. Filter Based on Multiple Conditions:
Filter numbers between 10 and 20:
numbers = [10, 25, 7, 33, 15] # Filter numbers between ten and twenty filtered_result = [n for n in numbers if 10 <= n <= 20] print("Numbers between 10 and 20:", filtered_result)
The result:
Numbers between 10 and 20: [10, 15]
5. Filter Strings of a Certain Length:
Filter words with length greater than 5:
words = ['apple', 'banana', 'orange', 'melon'] # Filter words of length greater than five filtered_result = [w for w in words if len(w) > 5] print("Words of length greater than 5:", filtered_result)
The result:
Words of length greater than 5: ['banana', 'orange']