Underoos
Underoos

Reputation: 5190

How to ignore specific elements being added to Python list

I have a python list. Let's say it's an empty list. Is there any way that I can make the list ignore specifc characters that when someone tries to add, at the time of list creation itself.

Suppose I want to ignore all the '.' characters to be ignored when someone tries to append the character usinng list.append('.').

Is there any way to mention that at the time of list creation itself?

Upvotes: 9

Views: 5146

Answers (4)

Vishvajit Pathak
Vishvajit Pathak

Reputation: 3731

class IgnoreList(list):

    def __init__(self, ignore_me):
        self.ignore_me = ignore_me

    def check(self, v):
        return v == self.ignore_me

    def append(self, v):
        if not self.check(v):
            super(IgnoreList, self).append(v)


my_list = IgnoreList('x')        # `x` to be ignored here
my_list.append('a')
my_list.append('b')
my_list.append('x')
my_list.append('c')
print my_list

######OUTPUT########
['a', 'b', 'c']

Upvotes: 2

Joe Iddon
Joe Iddon

Reputation: 20434

You could create a special appending function which modifies the list in place if the character is not a '.':

def append_no_dot(l, c):
   if c != '.': l.append(c)

>>> l = ['a','b']
>>> append_no_dot(l, 'c')
>>> append_no_dot(l, '.')
>>> l
['a', 'b', 'c']

Upvotes: 2

Kevin Koehler
Kevin Koehler

Reputation: 144

The best way to do this in python would be to create a new class with the desired behaviour

>>> class mylist(list):
...     def append(self, x):
...             if x != ".":
...                     super().append(x)
... 
>>> l = mylist()
>>> l.append("foo")
>>> l
['foo']
>>> l.append(".")
>>> l
['foo']

Upvotes: 3

StubbyAngel9
StubbyAngel9

Reputation: 96

I don't think you should do this, but if you really have to, you could subclass a list like so:

class IgnoreList(list):
    def append(self, item, *args, **kwargs):
        if item == '.':
            return
        return super(IgnoreList, self).append(item)

But is horribly un-pythonic. A better solution is to just check the value before calling append.

if value != '.':
    my_list.append(value)

Upvotes: 3

Related Questions