Is there an easy way to remove a list item by value?

a = [1, 2, 3, 4] b = a.index(6) del a[b] print a 

The following error is shown above:

 Traceback (most recent call last): File "D:\zjm_code\a.py", line 6, in <module> b = a.index(6) ValueError: list.index(x): x not in list 

So I have to do this:

 a = [1, 2, 3, 4] try: b = a.index(6) del a[b] except: pass print a 

But is there an easier way to do this?

+874
python list
May 08 '10 at 7:48 a.m.
source share
22 answers

To remove the first occurrence of an item in a list, simply use list.remove :

 >>> a = ['a', 'b', 'c', 'd'] >>> a.remove('b') >>> print a ['a', 'c', 'd'] 

Keep in mind that it does not delete all occurrences of your element. Use a list comprehension for this.

 >>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20] >>> a = [x for x in a if x != 20] >>> print a [10, 30, 40, 30, 40, 70] 
+1452
May 08 '10 at 7:56 a.m.
source share

Normally, Python will throw an exception if you tell it to do something that it cannot, so you have to do this:

 if c in a: a.remove(c) 

or

 try: a.remove(c) except ValueError: pass 

An exception is not necessarily bad if you expect it and handle it properly.

+171
May 08 '10 at 8:02
source share

You can do

 a=[1,2,3,4] if 6 in a: a.remove(6) 

but above you need to look for 6 in the list 2 times, so try, but it will be faster

 try: a.remove(6) except: pass 
+76
May 08 '10 at 7:57
source share

Consider:

 a = [1,2,2,3,4,5] 

To output all occurrences, you can use the filter function in python. For example, it would look like this:

 a = list(filter(lambda x: x!= 2, a)) 

Thus, it will save all the elements a! = 2.

To just take one of the elements, use

 a.remove(2) 
+54
Aug 11 '14 at 19:55
source share

Here's how to do it inplace (without understanding the list):

 def remove_all(seq, value): pos = 0 for item in seq: if item != value: seq[pos] = item pos += 1 del seq[pos:] 
+14
May 08 '10 at 14:57
source share

If you know what value to remove, here is a simple way (no matter how I think, anyway):

 a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4] while a.count(1) > 0: a.remove(1) 

You will receive [0, 0, 2, 3, 4]

+12
Mar 28 '13 at 9:20
source share

Another option is to use a set instead of a list if the set is applicable in your application.

IE, if your data is not ordered and have no duplicates, then

 my_set=set([3,4,2]) my_set.discard(1) 

is faultless.

Often a list is simply a convenient container for items that are actually disordered. There are questions about how to remove all occurrences of an item from a list. If you do not want to cheat in the first place, it’s more convenient again.

 my_set.add(3) 

does not change my_set from above.

+11
Mar 01 '16 at 23:13
source share

As pointed out in many other answers, list.remove() will work, but list.remove() ValueError if the item was not in the list. In python 3.4+ there is an interesting approach to solving this problem using an overwhelming context manager :

 from contextlib import suppress with suppress(ValueError): a.remove('b') 
+10
Sep 19 '17 at 11:36 on
source share

Finding a value in a list and then deleting this index (if one exists) is easier to do simply by using the delete list method:

 >>> a = [1, 2, 3, 4] >>> try: ... a.remove(6) ... except ValueError: ... pass ... >>> print a [1, 2, 3, 4] >>> try: ... a.remove(3) ... except ValueError: ... pass ... >>> print a [1, 2, 4] 

If you do this often, you can complete it in a function:

 def remove_if_exists(L, value): try: L.remove(value) except ValueError: pass 
+8
May 08 '10 at 7:58 a.m.
source share

This example runs quickly and removes all instances of the 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] 
+7
Aug 30 '15 at 15:43
source share

If your elements are different, then a simple difference in settings will be made.

 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] 
+7
Aug 11 '16 at 14:12
source share

in one line:

 a.remove('b') if 'b' in a else None 

sometimes it is useful

+7
Nov 23 '18 at 13:02
source share

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] >>> 
+2
Apr 05 '17 at 11:30
source share

Overwrite the list with all but the items you want to delete.

 >>> s = [5,4,3,2,1] >>> s[0:2] + s[3:] [5, 4, 2, 1] 
+2
Apr 7 '17 at 17:26
source share

With a for loop and condition:

 def cleaner(seq, value): temp = [] for number in seq: if number != value: temp.append(number) return temp 

And if you want to delete some, but not all:

 def cleaner(seq, value, occ): temp = [] for number in seq: if number == value and occ: occ -= 1 continue else: temp.append(number) return temp 
+2
May 05 '17 at 9:12 pm
source share
  list1=[1,2,3,3,4,5,6,1,3,4,5] n=int(input('enter number')) while n in list1: list1.remove(n) print(list1) 
+1
Jul 24 '17 at 16:54
source share

Say, for example, we want to remove all 1 from x. Here's how I do it:

 x = [1, 2, 3, 1, 2, 3] 

Now this is a practical use of my method:

 def Function(List, Unwanted): [List.remove(Unwanted) for Item in range(List.count(Unwanted))] return List x = Function(x, 1) print(x) 

And this is my one line method:

 [x.remove(1) for Item in range(x.count(1))] print(x) 

Both give this as a result:

 [2, 3, 2, 3, 2, 3] 

Hope this helps. PS, please note that this was written in version 3.6.2, so you may need to configure it for older versions.

+1
Sep 19 '17 at 11:31 on
source share

Maybe your solutions work with integers, but it doesn’t work with dictionaries for me.

On the one hand, deleting () does not work for me. But perhaps this works with basic types. I assume the code below is also a way to remove items from a list of objects.

On the other hand, "del" is also not working properly. In my case, using python 3.6: when I try to remove an item from the list using the for command using the del command, python changes the index in the process and bucle stops prematurely before the time runs out. This only works if you delete item by item in reverse order. Thus, you do not change the index of the array of pending elements when you pass it

Then I 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}, ...]

You can also do more pythonic using the enumeration:

 for i, element in enumerate(reversed(list)): if condition(element): del list[(i+1)*-1] print(list) 
+1
Nov 23 '18 at 11:44
source share
 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] 
0
Apr 02 '18 at 20:56
source share

This removes all instances of "-v" from the sys.argv array and not sys.argv complaints if no instance is found:

 while "-v" in sys.argv: sys.argv.remove('-v') 

You can see the code in action in the speechToText.py file:

 $ 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'] 
0
Sep 13 '18 at 15:43
source share

syntax: lst.remove(x)

For example:

 lst = ['one', 'two', 'three', 'four', 'two'] lst.remove('two') #it will remove first occurence of 'two' in a given list del lst[2] #delete item by index value print(lst) 
-one
Apr 02 '19 at 9:06
source share

Yes. This is what I found most useful:

 import sys a = [1, 2, 3, 4] y = 0 if y < 1: a.remove(1) print len(a) else: sys.exit() 

Now .remove() accepts only one argument, so you can remove only one integer from the list.

-3
Aug 28 '15 at 19:51
source share



All Articles