Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to wrapper built-in list in python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading