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
This example is fast and will delete all instances of a value from the list:
a = [1,2,3,1,2,3,4]
while True:
try:
a.remove(3)
except:
break
print a
>>> [1, 2, 1, 2, 4]
Overwrite the list by indexing everything except the elements you wish to remove
>>> s = [5,4,3,2,1]
>>> s[0:2] + s[3:]
[5, 4, 2, 1]
More generally,
>>> s = [5,4,3,2,1]
>>> i = s.index(3)
>>> s[:i] + s[i+1:]
[5, 4, 2, 1]
If your elements are distinct, then a simple set difference will do.
c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]
This removes all instances of "-v"
from the array sys.argv
, and does not complain if no instances were found:
while "-v" in sys.argv:
sys.argv.remove('-v')
You can see the code in action, in a file called speechToText.py
:
$ python speechToText.py -v
['speechToText.py']
$ python speechToText.py -x
['speechToText.py', '-x']
$ python speechToText.py -v -v
['speechToText.py']
$ python speechToText.py -v -v -x
['speechToText.py', '-x']
arr = [1, 1, 3, 4, 5, 2, 4, 3]
# to remove first occurence of that element, suppose 3 in this example
arr.remove(3)
# to remove all occurences of that element, again suppose 3
# use something called list comprehension
new_arr = [element for element in arr if element!=3]
# if you want to delete a position use "pop" function, suppose
# position 4
# the pop function also returns a value
removed_element = arr.pop(4)
# u can also use "del" to delete a position
del arr[4]
We can also use .pop:
>>> lst = [23,34,54,45]
>>> remove_element = 23
>>> if remove_element in lst:
... lst.pop(lst.index(remove_element))
...
23
>>> lst
[34, 54, 45]
>>>