Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting array elements in python

All, I want to delete specific array elements of one array from the other. Here is an example. The arrays are a long list of words though.

A = ['at','in','the']
B = ['verification','at','done','on','theresa']

I would like to delete words that appear in A from B.

B = ['verification','done','theresa']

Here is what I tried so far

for word in A:
    for word in B:
        B = B.replace(word,"")

I am getting an error:

AttributeError: 'list' object has no attribute 'replace'

What should I use to get it?

like image 904
papu Avatar asked Aug 10 '26 19:08

papu


2 Answers

Using a list comprehension to get the full answer:

[x for x in B if x not in A]

However, you may want to know more about replace, so ...

python list has no replace method. If you just want to remove an element from a list, set the relevant slice to be an empty list. For example:

>>> print B
['verification', 'at', 'done', 'on', 'theresa']
>>> x=B.index('at')
>>> B[x:x+1] = []
>>> print B
['verification', 'done', 'on', 'theresa']

Note that trying to do the same thing with the value B[x] will not delete the element from the list.

like image 153
Foo Bah Avatar answered Aug 13 '26 10:08

Foo Bah


If you are ok to delete duplicates in B and don't care about order, you can stick up with sets:

>>> A = ['at','in','the']
>>> B = ['verification','at','done','on','theresa']
>>> list(set(B).difference(A))
['on', 'done', 'theresa', 'verification']

In this case you'll get a significant speedup as lookup in set is much faster than in list. Actually, in this case it's better A and B to be sets

like image 25
Marat Avatar answered Aug 13 '26 11:08

Marat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!