I want to remove a value from a list if it exists in the list (which it may not).
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
The abov
Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.
In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.
In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it
Then, Im used:
c = len(list)-1
for element in (reversed(list)):
if condition(element):
del list[c]
c -= 1
print(list)
where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]
Also You can do more pythonic using enumerate:
for i, element in enumerate(reversed(list)):
if condition(element):
del list[(i+1)*-1]
print(list)