By riza


2009-07-21 03:12:10 8 Comments

In Python remove() will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list?

This is what I have in mind:

>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]

22 comments

@Asir Ajmal 2019-07-10 15:00:15

I just did this for a list. I am just a beginner. A slightly more advanced programmer can surely write a function like this.

for i in range(len(spam)):
    spam.remove('cat')
    if 'cat' not in spam:
         print('All instances of ' + 'cat ' + 'have been removed')
         break

@jolvi 2019-05-02 11:57:17

Let

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

The simplest and efficient solution as already posted before is

>>> x[:] = [v for v in x if v != 2]
>>> x
[1, 3, 4, 3]

Another possibility which should use less memory but be slower is

>>> for i in range(len(x) - 1, -1, -1):
        if x[i] == 2:
            x.pop(i)  # takes time ~ len(x) - i
>>> x
[1, 3, 4, 3]

Timing results for lists of length 1000 and 100000 with 10% matching entries: 0.16 vs 0.25 ms, and 23 vs 123 ms.

Timing with length 1000

Timing with length 100000

@SaNaMeDiO 2019-03-01 02:03:05

hello =  ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#chech every item for a match
for item in range(len(hello)-1):
     if hello[item] == ' ': 
#if there is a match, rebuild the list with the list before the item + the list after the item
         hello = hello[:item] + hello [item + 1:]
print hello

['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

@parlad neupane 2019-03-01 03:00:32

please try to elaborate your answer with explanation.

@Ankit Sharma 2018-06-29 19:55:34

a = [1, 2, 2, 3, 1]
to_remove = 1
a = [i for i in a if i != to_remove]
print(a)

Perhaps not the most pythonic but still the easiest for me haha

@cipher 2018-08-12 18:09:06

If you didn't have built-in filter or didn't want to use extra space and you need a linear solution...

def remove_all(A, v):
    k = 0
    n = len(A)
    for i in range(n):
        if A[i] !=  v:
            A[k] = A[i]
            k += 1

    A = A[:k]

@Maz1978 2018-07-30 16:00:03

First solution, using filter.
Second solution, using list comprehension.

#If we want to remove all 2.
ls = [2, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 6, 2]

# 1-filter takes two arguments(condition,sequence)
   ls = list(filter(lambda x: x != 2, ls))

# 2-list comprehension
   ls = [x for x in ls if x != 2]

@rafiqul786 2016-03-31 20:01:01

Remove all occurrences of a value from a Python list

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list():
    for list in lists:
      if(list!=7):
         print(list)
remove_values_from_list()

Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

Alternatively,

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list(remove):
    for list in lists:
      if(list!=remove):
        print(list)
remove_values_from_list(7)

Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

@rafiqul786 2016-04-01 07:05:59

"Python 'nested for each if loop' within a function working with 100% accuracy!"

@kon psych 2016-05-31 04:48:36

You don't modify the list you just print the elements. Also naming a list as lists is confusing

@code developer 2018-04-25 08:59:57

What's wrong with:

Motor=['1','2','2'] For i in Motor: If i != '2': Print(i) Print(motor)

Using anaconda

@Ignacio Ara 2018-04-25 09:19:02

Please explain your lines of code so other users can understand its functionality. Thanks!

@Sergey Kozlovskiy 2017-05-04 10:26:39

About the speed!

import time
s_time = time.time()

print 'start'
a = range(100000000)
del a[:]
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 3.25

s_time = time.time()
print 'start'
a = range(100000000)
a = []
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 2.11

@Mark Rushakoff 2009-07-21 03:28:39

Functional approach:

2.x

>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]

3.x

>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]

or

>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]

@habnabit 2009-07-21 04:28:59

Use the list comprehension over the filter+lambda; the former is more readable in addition to generally more efficient.

@habnabit 2009-07-21 04:29:39

s/generally/generally being/

@coredumperror 2013-04-22 22:12:10

The code for habnabit's suggestion looks like this: [y for y in x if y != 2]

@Peter Nimroot 2016-08-13 15:25:41

I wouldn't call this solution the best. List comprehensions are faster and easier to understand while skimming through code. This would rather be more of a Perl way than Python.

@Aran-Fey 2018-06-04 07:11:03

-1 for directly invoking __ne__. Comparing two values is a far more complex process than just calling __eq__ or __ne__ on one of them. It may work correctly here because you're only comparing numbers, but in the general case that's incorrect and a bug.

@Charlie Parker 2018-06-15 20:15:20

@habnabit what is the list comprehension solution?

@habnabit 2018-06-21 20:06:38

@ltc 2019-07-02 23:34:12

@habnabit This is probably going to get downvoted by the python crew, but the statement that the list comprehension is more readable is probably in the general case false. The filter higher order function concept exists in many more programming languages than list comprehensions as a concept (much less the specific list comprehension syntax as it exists in Python). Though I agree that the list comprehension is the "right" way to do this task in Python, if any one is confused why this answer has twice as many upvotes as the "right" answer, that is why.

@CPSuperstore 2019-09-13 15:51:06

Here is the lambda/list compression code: remove_all = lambda x: [y for y in x if y != 2]

@Shameem 2016-11-23 05:26:50

See the simple solutions

Solution 1:

>>> [i for i in x if i != 2]

This will return a list having all elements of x without 2

Solution 2:

>>> while 2 in x : x.remove(2)

@Aran-Fey 2018-08-05 07:34:57

Both of those solutions have already been posted. Years ago.

@marco 2016-11-03 14:12:18

for i in range(a.count(' ')):
    a.remove(' ')

Much simpler I believe.

@Ortund 2016-11-03 14:39:38

please edit your answer so as to improve clarity. Please make it clear what exactly your recommended code does, why it works and why this is your recommendation. Please also correctly format your question so that code is clearly discernible from the rest of your answer.

@Amr 2016-07-08 06:02:21

you can do this

while 2 in x:   
    x.remove(2)

@Hamlett 2016-09-19 19:36:30

this doesn't remove all the occurrences

@Guillaume 2016-11-03 16:29:17

@Hamlet: please explain why it would not remove all the occurrences of 2, because I have a hard time understanding why it would not... oO

@Hamlett 2016-11-21 13:38:15

@Guillaume, It was edited, "while 2 in x" was not part of the code. Now it is and the code seems right. upvote ;)

@Guillaume 2016-11-21 13:48:47

Ok thanks, I understand now :) That's the most readable and concise answer IMHO

@cxxl 2016-11-25 14:55:43

That's a bad solution, since the list has to be traversed 2*n times for n occurrences of 2.

@Aman Mathur 2017-04-22 05:51:57

It is not recommended to add or remove from the list you are traversing. Bad practice IMHO.

@Aran-Fey 2018-08-05 07:36:19

This is a bad solution and it's already been posted.

@Jared Burrows 2013-02-02 03:52:04

To remove all duplicate occurrences and leave one in the list:

test = [1, 1, 2, 3]

newlist = list(set(test))

print newlist

[1, 2, 3]

Here is the function I've used for Project Euler:

def removeOccurrences(e):
  return list(set(e))

@rschwieb 2013-03-01 00:13:25

I needed to do this on a vector with 250k values, and it works like a charm.

@Jared Burrows 2013-03-01 05:30:55

are you doing something like project euler?

@rschwieb 2013-03-01 14:08:54

The answer is: yes! And I completely understand if having a vector that long sounds completely crazy to a competent programmer. I approach the problems there as a mathematician, not worrying about optimizing the solutions, and that can lead to solutions longer than the par. (Although I don't have any patience for solutions longer than 5 minutes.)

@Jared Burrows 2013-03-03 00:55:01

haha this is great. i used it for the same reason.

@asmeurer 2013-07-16 22:03:55

This will remove any ordering from the list.

@Jared Burrows 2013-07-17 00:32:27

This code snippet is only to remove occurrences. You will most likely have to resort after.

@drevicko 2014-06-15 11:47:25

@JaredBurrows perhaps because it doesn't answer the question as it currently stands, but a quite different question.

@Anoyz 2016-07-22 11:18:09

-1, this is not an answer to the OP's question. It is a solution to remove duplicates, which is a completely different matter.

@Martin Andersson 2012-06-11 10:32:47

At the cost of readability, I think this version is slightly faster as it doesn't force the while to reexamine the list, thus doing exactly the same work remove has to do anyway:

x = [1, 2, 3, 4, 2, 2, 3]
def remove_values_from_list(the_list, val):
    for i in range(the_list.count(val)):
        the_list.remove(val)

remove_values_from_list(x, 2)

print(x)

@djsmith 2012-10-14 03:55:43

For the list you show in your code, this approach is about 36% slower than the list comprehension method (which returns a copy), according to my measurement.

@Martin Andersson 2012-10-15 08:01:44

Good you noticed that. However, because I think it might have slipped your judgement, I was comparing my version with the very first proposal made by the question author.

@MaxU 2016-06-04 09:01:52

Numpy approach and timings against a list/array with 1.000.000 elements:

Timings:

In [10]: a.shape
Out[10]: (1000000,)

In [13]: len(lst)
Out[13]: 1000000

In [18]: %timeit a[a != 2]
100 loops, best of 3: 2.94 ms per loop

In [19]: %timeit [x for x in lst if x != 2]
10 loops, best of 3: 79.7 ms per loop

Conclusion: numpy is 27 times faster (on my notebook) compared to list comprehension approach

PS if you want to convert your regular Python list lst to numpy array:

arr = np.array(lst)

Setup:

import numpy as np
a = np.random.randint(0, 1000, 10**6)

In [10]: a.shape
Out[10]: (1000000,)

In [12]: lst = a.tolist()

In [13]: len(lst)
Out[13]: 1000000

Check:

In [14]: a[a != 2].shape
Out[14]: (998949,)

In [15]: len([x for x in lst if x != 2])
Out[15]: 998949

@user5064329 2015-06-30 07:29:32

p=[2,3,4,4,4]
p.clear()
print(p)
[]

Only with Python 3

@Erich 2017-08-28 22:26:28

Hilariously, this is within the scope of the question asked and is correct.

@funk 2014-10-17 06:42:03

Repeating the solution of the first post in a more abstract way:

>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> while 2 in x: x.remove(2)
>>> x
[1, 3, 4, 3]

@horta 2016-06-21 21:43:57

Definitely the most readable solution imo.

@Hannes 2016-09-07 04:45:29

It's O(n*n), though.

@penta 2019-03-28 04:01:01

@Hannes would not it be O(n) since it is going through the loop just once & at the same time removing the item ?

@Hannes 2019-04-02 06:13:20

Consider x = [1] * 10000 + [2] * 1000. The loop body executes 1000 times and .remove() has to skip 10000 elements every time it's invoked. That smells like O(n*n) to me but is no proof. I think the proof would be to assume that the number of 2s in the list is proportional to its length. That proportionality factor then disappears in big-O notation. The best case, though, of only a constant number of 2s in the list, is not O(n^2), just O(2n) which is O(n).

@Paul S 2014-07-04 16:04:21

All of the answers above (apart from Martin Andersson's) create a new list without the desired items, rather than removing the items from the original list.

>>> import random, timeit
>>> a = list(range(5)) * 1000
>>> random.shuffle(a)

>>> b = a
>>> print(b is a)
True

>>> b = [x for x in b if x != 0]
>>> print(b is a)
False
>>> b.count(0)
0
>>> a.count(0)
1000

>>> b = a
>>> b = filter(lambda a: a != 2, x)
>>> print(b is a)
False

This can be important if you have other references to the list hanging around.

To modify the list in place, use a method like this

>>> def removeall_inplace(x, l):
...     for _ in xrange(l.count(x)):
...         l.remove(x)
...
>>> removeall_inplace(0, b)
>>> b is a
True
>>> a.count(0)
0

As far as speed is concerned, results on my laptop are (all on a 5000 entry list with 1000 entries removed)

  • List comprehension - ~400us
  • Filter - ~900us
  • .remove() loop - 50ms

So the .remove loop is about 100x slower........ Hmmm, maybe a different approach is needed. The fastest I've found is using the list comprehension, but then replace the contents of the original list.

>>> def removeall_replace(x, l):
....    t = [y for y in l if y != x]
....    del l[:]
....    l.extend(t)
  • removeall_replace() - 450us

@Dannid 2016-03-01 17:58:07

Why not just reassign the new list under the old address then? def remove_all(x, l): return [y for y in l if y != x] then l = remove_all(3,l)

@Paul S 2016-03-10 17:25:01

@Dannid That's the second method in the first code box. It creates a new list, and you're not modifying the old list. Any other references to the list will remain unfiltered.

@Dannid 2016-03-14 21:19:41

Ah, right. I got so caught up in defining a method, I overlooked the simple assignment you'd already done.

@Michael Clemmons 2011-01-06 19:27:17

I believe this is probably faster than any other way if you don't care about the lists order, if you do take care about the final order store the indexes from the original and resort by that.

category_ids.sort()
ones_last_index = category_ids.count('1')
del category_ids[0:ones_last_index]

@Shedokan 2013-04-27 10:31:21

I understand where your'e going, but this code won't work since you need also the start index and not just 0.

@A. Coady 2009-07-21 03:33:13

You can use slice assignment if the original list must be modified, while still using an efficient list comprehension (or generator expression).

>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> x[:] = (value for value in x if value != 2)
>>> x
[1, 3, 4, 3]

@riza 2009-07-21 03:36:26

This is what filter do right.

@E.M. 2009-07-21 03:47:42

@Selinap: filter does not modify the list, it returns a new list.

@A. Coady 2009-07-22 23:24:42

filter and list comprehensions don't modify a list. slice assignment does. and the original example does.

@Hannes 2016-09-07 05:06:21

I like this because it modifies the list that x refers to. If there are any other references to that list, they will be affected too. This is in contrast to the x = [ v for v in x if x != 2 ] proposals, that create a new list and change x to refer to it, leaving the original list untouched.

@mhawke 2009-07-21 03:17:58

You can use a list comprehension:

def remove_values_from_list(the_list, val):
   return [value for value in the_list if value != val]

x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
print x
# [1, 3, 4, 3]

@riza 2009-07-21 03:19:42

But, this way, it will check for each item in the list.

@Alexander Ljungberg 2009-07-21 03:20:40

How would you remove items without checking them?

@John Y 2009-07-21 03:20:58

This doesn't modify the original list but returns a new list.

@riza 2009-07-21 03:21:53

@Alexander Ljungberg: Is there a way to reduce the number of checking?

@John Kugelman 2009-07-21 03:24:59

@Selinap: No, this is optimal as it scans the list only once. In your original code both the in operator and remove method scan the entire list (up until they find a match) so you end up scanning the list multiple times that way.

@Alexander Ljungberg 2009-07-21 03:26:16

@Selinap: if you structure your data ahead of time in something like a binary tree you can hunt down all instances of a certain value without having to check all values in the data. What are you trying to accomplish?

@mhawke 2009-07-21 03:27:03

@John Y: "This doesn't modify the original list but returns a new list"... and then rebinds it - probably much faster than removing in place.

@Alex Martelli 2009-07-21 03:33:55

@mhawke, @John Y: just use x[:] = ... instead of x = and it will be "in-place" rather than just rebinding the name 'x' (speed is essentially the same and MUCH faster than x.remove can be!!!).

@Glenn Maynard 2009-07-21 03:36:32

Removing in-place can be very fast if you don't care about the order: move the last item over the one you're deleting, then when you're done scanning, truncate the items off the end. If you're not removing many elements, this may be faster in a lower level language--it moves less memory around. I suspect it's a wash in Python.

@Glenn Maynard 2009-07-21 03:39:05

Doing x[:] = y is probably going to make a second memory copy of the list, though, which will be slower (not by much, at least for typical small lists).

@Benjamin 2012-09-29 10:47:14

I vote this up because after 6 years of Python I still don't understand Lambdas :)

@Houdini 2013-05-24 14:23:57

@Benjamin Lambdas are also known as 'anonymous functions'. Basically, they are functions you create on-the-fly, usually for a specific purpose, and just kind of injected into a certain spot in your code. As a side note, I am not entirely sure about Python, but in other languages (like Scheme), every function that you write is actually INTERNALLY converted and stored as a Lambda expression. Giving it some name to reference it by, and referring to it by that name, is syntactic sugar of sorts for the underlying Lambda expression.

Related Questions

Sponsored Content

19 Answered Questions

[SOLVED] Accessing the index in 'for' loops?

  • 2009-02-06 22:47:54
  • Joan Venge
  • 1872574 View
  • 3227 Score
  • 19 Answer
  • Tags:   python loops list

38 Answered Questions

[SOLVED] What does the "yield" keyword do?

15 Answered Questions

[SOLVED] How to clone or copy a list?

19 Answered Questions

[SOLVED] How to remove an element from a list by index?

  • 2009-03-09 18:16:11
  • Joan Venge
  • 2307333 View
  • 1306 Score
  • 19 Answer
  • Tags:   python list

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3544074 View
  • 3474 Score
  • 21 Answer
  • Tags:   python directory

28 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3405582 View
  • 2805 Score
  • 28 Answer
  • Tags:   python list indexing

60 Answered Questions

[SOLVED] How do you split a list into evenly sized chunks?

22 Answered Questions

[SOLVED] How can I count the occurrences of a list item?

  • 2010-04-08 13:30:00
  • weakish
  • 1438976 View
  • 1372 Score
  • 22 Answer
  • Tags:   python list count

25 Answered Questions

[SOLVED] How do I concatenate two lists in Python?

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

Sponsored Content