0

How can I do that?

>>> a
['eins', 'zwei', 'drei', 'vier', 'fünf']
>>> b
['eins', 'zwei', 'drei']
>>> c = a - b

This doesn't work, too.

c = a[:].remove(b)
2
  • 1
    Just use sets. For example set(a).difference(b)
    – vaultah
    Commented Dec 3, 2015 at 15:39
  • 2
    [i for i in a if i not in b] Commented Dec 3, 2015 at 15:49

3 Answers 3

2

If you don't need repeated elements you could use sets as jadelord said

If list a has repeated elements and you need them you should use

c = list(filter(lambda x: x not in b, a))

Or

c = [x for x in a if x not in b]
1

What you are looking for is a functionality associated with the set datatype in python. Not lists!

This should solve your problem:

c = list(set(a) - set(b))
2
  • This is only if OP doesn't want repeated elements
    – Mr. E
    Commented Dec 3, 2015 at 16:05
  • If there are repetitions in list a then, list comprehension mentioned in the comments above is the best alternative.
    – jadelord
    Commented Dec 3, 2015 at 16:12
0

Instances of Set and ImmutableSet both provide the following operations:

Operation        Equivalent     Result
len(s)                          cardinality of set s
x in s                          test x for membership in s
x not in s                      test x for non-membership in s
s.issubset(t)      s <= t       test whether every element in s is in t
s.issuperset(t)    s >= t       test whether every element in t is in s
s.union(t)          s | t       new set with elements from both s and t
s.intersection(t)   s & t       new set with elements common to s and t
s.difference(t)     s - t       new set with elements in s but not in t
s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both
s.copy()                        new set with a shallow copy of s

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.