4

If I have lists:

a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]

c = a * b

should give me:

c = [4, 5]

and

c = a - b

should give me:

c = [1, 2, 3]

Is this available for Python or do I have to write it myself?

Would the same work for tuples? I will likely use lists as I will be adding them, but just wondering.

4
  • 3
    Do you care about multiplicity and/or order? If not, you can simply use sets. Commented Nov 24, 2013 at 19:00
  • 5
    Python's set class has built in difference and intersection methods. The only caveat is losing duplicates if that matters. Commented Nov 24, 2013 at 19:01
  • 1
    @squiguy: in which case a Counter would maintain the counts. Commented Nov 24, 2013 at 19:03
  • No I don't. I just want the list/collection and then query if a certain integer is in the group. Commented Nov 24, 2013 at 19:07

1 Answer 1

17

If the order doesn't matter, you can use set for this. It has intersection and difference implemented.

>>> a = set([1, 2, 3, 4, 5])
>>> b = set([4, 5, 6, 7, 8])
>>> a.intersection(b)
set([4, 5])
>>> a.difference(b)
set([1, 2, 3])

Here is the info of time complexities of these operations: https://wiki.python.org/moin/TimeComplexity#set. Notice, that the order of subtrahends changes operation complexity.

If element can occur several times (formally it is called multiset), you can use Counter:

>>> from collections import Counter
>>> a = Counter([1, 2, 3, 4, 4, 5, 5])
>>> b = Counter([4, 4, 5, 6, 7, 8])
>>> a - b
Counter({1: 1, 2: 1, 3: 1, 5: 1})
>>> a & b
Counter({4: 2, 5: 1})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.