Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify python collections by filtering in-place?

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?

like image 225
Zaur Nasibov Avatar asked Nov 07 '11 13:11

Zaur Nasibov


People also ask

How do I filter a collection in Python?

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 .

Does filter modify the original array Python?

The filter() method does not change the original array.

What is filter () function in Python?

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.


1 Answers

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.

like image 90
Sven Marnach Avatar answered Sep 17 '22 17:09

Sven Marnach