manyspikes

Set operations

Initialising environment...

Sets also support common mathematical operations on sets, such as unions and intersections.

x = {1, 2, 3} y = x.union({3, 4, 5}) z = y.intersection({1, 5})

Note that the union and intersection methods return new sets, they do not modify the original set.

The | and & operators can equivalently be used instead of the union and intersection methods, respectively:

z = x | y z = x & y

Here are some common methods for working with sets:

  • x.difference(y) or x - y returns a set of elements present in x but not in y
  • x.symmetric_difference(y) or x ^ y returns a set of elements present in x or y but not in both
  • x.isdisjoint(y) returns True if x and y have no elements in common and False otherwise
  • x.issubset(y) or x <= y returns True if x is a subset of y
  • x.issuperset(y) or x >= y returns True if x is a superset of y

The operations above do not modify any of the sets x or y, contrary to the following operations:

  • x.add(1) adds the value 1 to the set x
  • x.remove(1) removes the value 1 from the set x
  • x.clear() removes all elements in from the set x

Instructions

Define a set x containing the values 3, 4 and 5. Then, define another set y containint the values 4, 5 and 6.

Compute a set z which contains all elements that belong to x or to y but not to both.

Note: There are a few ways of achieving this using the operations above. Feel free to experiment!