How do I filter lists in Python with examples?

In Python, filtering lists can be done using various methods such as list comprehensions, the `filter()` function, and loops. Below are examples illustrating these different approaches.

1. Using List Comprehensions

List comprehensions offer a concise way to filter lists. The syntax allows you to create a new list by applying an expression to each element in the original list, along with an optional condition.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [num for num in numbers if num % 2 == 0] print(even_numbers) # Output: [2, 4, 6, 8, 10]

2. Using the `filter()` Function

The `filter()` function constructs an iterator from elements of a list for which a function returns true. You can use a lambda function for a more concise approach.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # Output: [2, 4, 6, 8, 10]

3. Using Loops

In cases where more complex logic is required, a traditional loop can be used to filter items in a list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [] for num in numbers: if num % 2 == 0: even_numbers.append(num) print(even_numbers) # Output: [2, 4, 6, 8, 10]

Python filter lists list comprehensions filter function Python loops