🔍 Filtering Lists
Python provides multiple ways to filter lists, allowing you to extract elements that meet specific criteria. Understanding these methods is essential for data processing and analysis.
# Basic list filtering
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # [2, 4, 6, 8, 10]
🎯 Filtering Methods
Python offers several approaches to filter lists.
Basic Examples
# Different ways to filter lists
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# List comprehension
even_numbers = [x for x in numbers if x % 2 == 0]
print(f"Even numbers: {even_numbers}")
# Filter function
def is_even(x):
return x % 2 == 0
even_numbers = list(filter(is_even, numbers))
print(f"Using filter(): {even_numbers}")
# For loop
even_numbers = []
for x in numbers:
if x % 2 == 0:
even_numbers.append(x)
print(f"Using for loop: {even_numbers}")
🔍 Advanced Filtering
Python allows complex filtering conditions and multiple criteria.
# Advanced filtering examples
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Multiple conditions
filtered = [x for x in numbers if x % 2 == 0 and x > 5]
print(f"Even numbers > 5: {filtered}")
# Using lambda with filter
filtered = list(filter(lambda x: x % 2 == 0 and x > 5, numbers))
print(f"Using lambda: {filtered}")
# Filtering with None values
values = [1, None, 2, None, 3]
filtered = [x for x in values if x is not None]
print(f"Non-None values: {filtered}")
🎯 Key Takeaways
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.