papu
papu

Reputation: 35

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?

Upvotes: 3

Views: 17151

Answers (3)

Marat
Marat

Reputation: 15738

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

Upvotes: 3

OneOfOne
OneOfOne

Reputation: 99224

You could also try removing the elements from B, ex :

A = ['at','in','the']
B = ['verification','at','done','on','theresa']
print B
for w in A:
    #since it can throw an exception if the word isn't in B
    try: B.remove(w)
    except: pass
print B

Upvotes: 1

Foo Bah
Foo Bah

Reputation: 26271

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.

Upvotes: 3

Related Questions