Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 282
Underoos Avatar asked Aug 22 '18 20:08

Underoos


People also ask

How do you exclude an item from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do you ignore a value in a list Python?

If you use the list. pop() method to remove an item from a list, you might get an IndexError . You can use a try/except statement to ignore or handle the error.


2 Answers

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)
like image 59
StubbyAngel9 Avatar answered Sep 18 '22 01:09

StubbyAngel9


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']
like image 34
Kevin Koehler Avatar answered Sep 18 '22 01:09

Kevin Koehler