Python 3 list and set operations

Python 3 offer elegant and efficient way to deal with lists and operations like:

  • intersection - elements from list1 and list2
  • union - all unique elements from both lists
  • union all - all unique elements from both lists with repetition
  • subtraction/difference - elements from list1 not in list2

Depending on your needs you can write your own version. The solution offered by the language is good enough for most cases and situation.

Compare two lists in Python 3 with sets

If you deal with huge lists or the performance is important for you then you can use set in order to speed up your applications. Using sets gives you also easy way to find the difference or the same elements of two and more lists. In the next code example are shown most common list operations:

x = ['a','b','c','d']
y = ['b','c','d','e']

print (list (set(x) - set(y)))
print (list (set(y) - set(x)))
print (list (set(x) & set(y)))
print (list (set(x) | set(y)))
print (list (set(x) ^ set(y)))

result:

x - y:       ['a']
y - x:       ['e']
x & y:       ['d', 'c', 'b']
x | y:       ['b', 'e', 'd', 'c', 'a']
x ^ y:       ['a', 'e']

It's important to mention that this example can work even with lists with different size.

Official documentation for List and Set

If you are interested you can have a look in this article: sets — Unordered collections of unique elements

Two interesting tables about set operations:

  • set and ImmutableSet operations
Operation Equivalent Result
len(s)   number of elements in set s (cardinality)
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
  • List operations available in Set
Operation Equivalent Result
s.update(t) s |= t return set s with elements added from t
s.intersection_update(t) s &= t return set s keeping only elements also found in t
s.difference_update(t) s -= t return set s after removing elements found in t
s.symmetric_difference_update(t) s ^= t return set s with elements from s or t but not both
s.add(x)   add element x to set s
s.remove(x)   remove x from set s; raises KeyError if not present
s.discard(x)   removes x from set s if present
s.pop()   remove and return an arbitrary element from s; raises KeyError if empty
s.clear()   remove all elements from set s