user9886033
user9886033

Reputation:

Python3: How to remove list items with another list item(s)

I have two lists:

     a = ['eggs', 'eggs', 'spam', 'ham', 'eggs']

and:

     b = ['e', 'e']

I want to be able to remove eggs from list a. According to the e's in list b. so my ideal output would be:

     a = ['spam', 'ham', 'eggs']

Since there is only 2 e's in list a.

I have tried:

     [a.remove('eggs') for e in b if e =='e' for eggs in a if eggs=='eggs']

The problem is that that this list-comprehension removes all eggs. show me the pythonic way!

Upvotes: 0

Views: 48

Answers (2)

Olivier Melançon
Olivier Melançon

Reputation: 22304

You should not use lst.remove in a list comprehension. Since this method mutates your list and returns None, you are not interested in the output and should use a for-loop instead.

You can use lst.count to find out the number of occurences of 'e' in your second list and then use lst.remove on the second list.

a = ['eggs', 'eggs', 'spam', 'ham', 'eggs']
b = ['e', 'e']

for _ in range(b.count('e')):
    a.remove('eggs')

print(a) # ['spam', 'ham', 'eggs']

Upvotes: 0

Luke Graham
Luke Graham

Reputation: 21

a = ['eggs', 'eggs', 'spam', 'ham', 'eggs']
b = ['e', 'e']

for e in b:
    if e == "e":
        a.remove("eggs")

print(a)

This is not one line but it should work.

Upvotes: 2

Related Questions