To filter elements of a list based on a condition in Python, you can use list comprehensions or the filter function along with lambda expressions.
In this example,
numbers
with integer values.numbers = [1, 2, 3, 4, 5]
threshold = 3
filtered_numbers = [num for num in numbers if num > threshold]
print('Filtered list:', filtered_numbers)
Filtered list: [4, 5]
In this example,
words
with string values.filter
function along with a lambda expression to filter elements containing a specific substring.words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
substring = 'erry'
filtered_words = list(filter(lambda word: substring in word, words))
print('Filtered list:', filtered_words)
Filtered list: ['cherry', 'elderberry']
In this tutorial, we learned How to Filter Elements of a List based on a Condition in Python language with well detailed examples.