How to wrapper built-in list in python?

Question:

I want to define a class ListWrapper that has all list behaviors and also has a filter method.
It should work like this:

ls = [1, 2, 3, 4, 5]
ls = ListWrapper(ls)
ls.filter(lambda x: True if x % 2 == 0 else False)
print(ls)
# out: [2, 4]

what should I do?


This is my attempt that failed

class ListWrapper(list):
    def filter(self, func):
        filtered_list = list(filter(func, self))
        self = ListWrapper(filtered_list)
ls = [1, 2, 3, 4, 5]
ls = ListWrapper(ls)
ls.filter(lambda x: True if x % 2 == 0 else False)
print(ls)
# out: [1, 2, 3, 4, 5]
Asked By: zhixin

||

Answers:

You should modify the ListWrapper object in place, and not just substitute it with a new ListWrapper, otherwise the original list remains the same.

class ListWrapper(list):
    def filter(self, func):
        filtered_list = list(filter(func, self))
        self.clear()
        self.extend(filtered_list)

This then should execute the way you want:

ls = [1, 2, 3, 4, 5]
ls = ListWrapper(ls)
ls.filter(lambda x: x % 2 == 0)
print(ls) #prints [2,4]

Note that

lambda x: True if x % 2 == 0 else False

can be better re-written as

lambda x: x % 2 == 0
Answered By: Domiziano Scarcelli

To make your implementation work, you can modify the original ListWrapper object in place by removing all its elements and appending the filtered elements using the clear() and extend() methods.
Here’s an updated implementation that should work as expected:

 class ListWrapper(list):
    def filter(self, func):
        filtered_list = list(filter(func, self))
        self.clear()
        self.extend(filtered_list)
ls = [1, 2, 3, 4, 5]
ls = ListWrapper(ls)
ls.filter(lambda x: True if x % 2 == 0 else False)
print(ls)
# out: [2, 4]
Answered By: dostogircse171
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.