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?
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.
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.
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)
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With