0

Possible Duplicate:
Remove all occurences of a value from a Python list

mylist = ['dogs', 'cats', 'cats']

If I type mylist.remove('cats'), it deletes only one cats in my list, but I want to delete all cats in my list without loops, because loops are going to crash the way I want to.

EDIT: it's a little trick to explain, for example, it's going to crash because I'm trying to develop a module to remove equal elements from a list. mylist[i] returns dogs firstly, I delete it, but after another loop, mylist[i] doesn't return dogs anymore, but cats. That's why I want to delete all instances in a single statement regardless of the index loop.

Community
  • 1
  • 1
jimjen
  • 3
  • 1
  • 3

3 Answers3

6

You can create a new list with a list comprehension to avoid an explicit loop:

mylist = [item for item in mylist if item != 'cats']
Gabe
  • 84,912
  • 12
  • 139
  • 238
  • Note that you can do `mylist[:] = ...` if you want to modify the list in-place, at a minor cost to efficiency (an extra copy). – Glenn Maynard Mar 13 '11 at 01:19
1

There is no built-in method for removing all elements from a list. You have to use a loop. What is wrong with:

In [129]: x=['dog','cat','cat']
In [136]: [elt for elt in x if elt!='cat']
Out[136]: ['dog']

?

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

Unless the supplied list copy must be modified inplace, I would suggest filter.

>>> x = itertools.ifilter(lambda x: x != 'foo', ['foo', 'foo', 'bar'])
>>> x
<itertools.ifilter object at 0xb70ba2ec>
>>> list(x)
['bar']
Bittrance
  • 2,202
  • 2
  • 20
  • 29