I was wondering, if there is way in Python to modify collections without creating new ones. E.g.:
lst = [1, 2, 3, 4, 5, 6]
new_lst = [i for i in lst if i > 3]
Works just fine, but a new collection is created. Is there a reason, that Python collections lack a filter()
method (or similar) that would modify the collection object in place?
Python has a built-in function called filter() that allows you to filter a list (or a tuple) in a more beautiful way. The filter() function iterates over the elements of the list and applies the fn() function to each element. It returns an iterator for the elements where the fn() returns True .
The filter() method does not change the original array.
The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.
If you want to do this in place, just use
lst[:] = [i for i in lst if i > 3]
This won't be faster or save any memory, but it changes the object in place, if this is the semantics you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With