To remove elements from a list based on a condition in Python, you can use list comprehension or the `filter` function.
In this example,
numbers
with some elements.numbers = [1, 2, 3, 4, 5]
threshold = 3
numbers = [x for x in numbers if x <= threshold]
print('Modified list after removing elements greater than {}: {}'.format(threshold, numbers))
Modified list after removing elements greater than 3: [1, 2, 3]
In this example,
names
with some elements.is_long_name
that returns True
if the length of the string is greater than a specified value.filter
function to filter elements based on the predicate condition.names = ['John', 'Alice', 'Michael', 'Emma']
max_length = 5
def is_long_name(name):
return len(name) > max_length
names = list(filter(lambda x: not is_long_name(x), names))
print('Modified list after removing long names:', names)
Modified list after removing long names: ['John', 'Alice', 'Emma']
In this tutorial, we learned How to Remove Element from List based on a Condition in Python language with well detailed examples.