Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all the occurrences of a certain value in a Python list? [duplicate]

Tags:

python

list

How to remove both occurrences of 333 from the below list?

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]

I typed the below script in the Python 2.7 command line

for num in a:
    if num == 333:
       a.remove(num)

But only the first occurrence of 333 is removed

 >>> a
 [-1, 1, 66.25, 333, 1234.5]

How to remove all the occurrences of the same element? I want to be able to specify the element of which I want all the occurrences be removed and get a new list by the same name or another

like image 235
Varuna Avatar asked Dec 03 '22 21:12

Varuna


2 Answers

Use a list comprehension here:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> [item for item in a if item != 333]
[-1, 1, 66.25, 1234.5]

Your approach didn't work because you're modifying a list while iterating over it.

for num in a[:]:  #iterate over a shallow copy
    if num == 333:
       a.remove(num)

To get a list of just unique items, use a set:

>>> seen = set()
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> [item for item in a if item not in seen and not seen.add(item)]
[-1, 1, 66.25, 333, 1234.5]

If order doesn't matter:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> list(set(a))
[66.25, 1, 333, -1, 1234.5]
like image 171
Ashwini Chaudhary Avatar answered Dec 09 '22 15:12

Ashwini Chaudhary


Since you ask how to remove elements, I would re-assign the list as a slice.

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> a[:] = [item for item in a if item != 333]

This will create a new list in memory, normally thats acceptable, but if you want to avoid this without calling remove, which would check against the same items multiple times.

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> for i in range(len(a) - 1, -1, -1):  # iterate over reversed indices's
>>>     if a[i] == 333:
>>>         del a[i]

This has the advantage that it removes the last items first (which is faster in CPython).

Note that removing items from the beginning-middle of lists in Python is not so optimal. no matter which method you use (del list[index] or list.remove), if the list is large and many items have to be removed this means Python needs to resize the list a lot, in that case I would recommend using list-comprehension to make a new list.

like image 23
ideasman42 Avatar answered Dec 09 '22 16:12

ideasman42