Remove element in list using list comprehension - Python
The improvement to your code (which is almost correct) would be:
list = ['A','B','C']
[var for var in list if var != 'A']
However, @frostnational's approach is better for single values.
If you are going to have a list of values to disallow, you can do that as:
list = ['A','B','C', 'D']
not_allowed = ['A', 'B']
[var for var in list if var not in not_allowed]
Simple lst.remove('A')
will work:
>>> lst = ['A','B','C']
>>> lst.remove('A')
['B', 'C']
However, one call to .remove
only removes the first occurrence of 'A'
in a list. To remove all 'A'
values you can use a loop:
for x in range(lst.count('A')):
lst.remove('A')
If you insist on using list comprehension you can use
>>> [x for x in lst if x != 'A']
['B', 'C']
The above will remove all elements equal to 'A'
.