3

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Also, B.pop(x), or even better B.remove('at') would work here.
B[x:x+1] = [] -> del B[x:x+1]
@Patrick one fringe benefit of presenting this array technique is that the same form can be used to insert multiple elements. For example, x=[1,2,3];x[1:2]=[5,6,7];x returns [1,5,6,7,3].
3

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

4 Comments

"lookup in set is much faster than in dictionary" -- I'm not sure quite what you mean here, as I don't see dictionaries in any of the other answers, but lookup in a set is basically the same as key lookup in a dictionary.
I think he meant "lookup in set is much faster than in list". The question is about lists, everyone is talking about lists, and this way it is a correct statement.
you're right, it's all about lists. Lookup in lis is O(n), lookup in set/dictionary is O(1)
However the result's order will be changed.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.