20

I have a list like this:

['A','B','C']

What I need is to remove one element based on the input I got in the function. For example, if I decide to remove A it should return:

['B','C']

I tried with no success

list = ['A','B','C']
[var for var in list if list[var] != 'A']

How can I do it? Thanks

The Condor
  • 1,034
  • 4
  • 16
  • 44
  • http://stackoverflow.com/questions/7016304/removing-elements-from-a-list – devnull May 07 '14 at 11:16
  • http://stackoverflow.com/questions/4915920/how-to-delete-an-item-in-a-list-if-it-exists-python/4915964#4915964 – jortizromo May 07 '14 at 11:19
  • 1
    No-one has actually pointed out your true mistake here: In the list comprehension, it will try to evaluate list['A'] which wont work for two reasons. 1) it's not a dict and 2) you're trying to use the value as the index – Tom Busby Jul 06 '16 at 12:24

7 Answers7

30

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'.

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • 1
    In my particular use case of very long lists, a list comprehension is blazingly faster than the lst.remove approach. So, I insist on using it! – Sol Jun 06 '21 at 21:05
  • 1
    Additionally the list comprehension allows to add conditional removal easily (remove if condition is true). great solution – Roberto Jun 24 '21 at 13:00
12

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]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

If you not sure whether the element exists or not, you might want to check before you delete:

if 'A' in lst:
    lst.remove('A')
user 923227
  • 2,528
  • 4
  • 27
  • 46
1
originalList=['A','B','C']
print([val for val in originalList if val!='A'])

This prints

['B', 'C']
0

You can just use the remove method of list. Just do list.remove('A') and it will be removed.

If you have the index of the item to be removed, use the pop method. list.pop(0).

anirudh
  • 4,116
  • 2
  • 20
  • 35
0

Find this simplified code:

list1 = [12,24,35,24,88,120,155]

while 24 in list1:

    list1.remove(24)

print(list1)

Best Luck!

Rarblack
  • 4,559
  • 4
  • 22
  • 33
0

You were really close:

list = ['A','B','C']
[var for var in list if list[list.index(var)] != 'A']

You tried to refer to a list item using a syntax that calls for an index value.

vezunchik
  • 3,669
  • 3
  • 16
  • 25