How do I filter lists in Python in pure Python?

Filtering lists in Python can be done using various techniques, primarily using list comprehensions, the `filter()` function, or simple loops. Below are some examples demonstrating how to filter lists effectively using pure Python techniques.

Python, filtering lists, list comprehensions, filter function, pure Python

This guide provides insights into filtering lists in Python using pure methods without relying on external libraries, making your code cleaner and more efficient.

        
# Example of filtering a list of numbers to get only even numbers

# Using list comprehension
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)  # Output: [2, 4, 6]

# Using filter function
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4, 6]

# Using a for loop
even_numbers = []
for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)
print(even_numbers)  # Output: [2, 4, 6]
        
    

Python filtering lists list comprehensions filter function pure Python