Open In App

Filtering Elements In List Comprehension

List comprehensions are a powerful and concise way to create lists in Python. One of their notable features is the ability to filter elements based on certain conditions. In this article, we will delve into the art of filtering elements in list comprehensions, showcasing simple methods to enhance the readability and efficiency of your code.

Syntax:



Here, expression is the operation performed on each item from the iterable that satisfies the specified condition. The if condition part is optional but crucial when it comes to filtering elements.

list = [expression for item in iterable if condition]

Filtering Elements In List Comprehensions

Below, are the example of Filtering Elements In List Comprehensions in Python.



Basic Conditional Filtering

In this example, below given code initializes a list of numbers from 1 to 10, uses a list comprehension to filter out even numbers, and then prints the resulting list of odd numbers: `[1, 3, 5, 7, 9]`.




original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = [x for x in original_list if x % 2 != 0]
print(filtered_list)

Output
[1, 3, 5, 7, 9]


Filtering Elements Using Multiple Conditions

In this example, given code initializes a list of numbers from 1 to 10, filters it using a list comprehension to include only elements greater than 3 and even, and then prints the resulting filtered list: `[4, 6, 8, 10]`.




original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = [x for x in original_list if x > 3 and x % 2 == 0]
print(filtered_list)

Output
[4, 6, 8, 10]


Filtering Strings Using List Comprehensions

In this example, below code initializes an original list of fruit names, filters it using a list comprehension to include only words with more than three characters.




original_list = ["apple", "banana", "ora", "kiw", "grape"]
filtered_list = [word for word in original_list if len(word) > 3]
print(filtered_list)

Output
['apple', 'banana', 'grape']


Filtering Elements Using the filter() Function

In this example, below code creates an original list of numbers from 1 to 10, then uses the `filter()` function with a lambda expression to create a new list (`filtered_list`) containing only the odd numbers.




original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = list(filter(lambda x: x % 2 != 0, original_list))
print(filtered_list)

Output
[1, 3, 5, 7, 9]


Conclusion

In Conclusion, leveraging list comprehensions for element filtering in Python not only streamlines code but also offers flexibility with concise and expressive syntax. These versatile constructs empower developers to efficiently handle various filtering scenarios, enhancing the overall readability and efficiency of Python programs.


Article Tags :