Sets are unordered, mutable collections of unique elements.

Sets have special methods to perform set operations like union, intersection, difference etc. with groups of items.

Set basics

Non-empty sets can be created by enclosing a sequence of comma-separated values in curly brackets:

>>> set1 = {1, 8, 4, 5, 6}
>>> type(set1)
<class 'set'>

Sets can also be created from a list or tuple using the set() constructor. Notice how all items which were duplicated in the list appear only once in the set:

>>> set2 = set([1, 3, 2, 3, 4, 3])
>>> set2
{1, 2, 3, 4}

Creating empty sets

Because curly brackets are also used to create dictionaries, it is not possible to create an empty set using braces. An empty pair of braces creates a dictionary, not a set:

>>> type({})
<type 'dict'>

To create an empty set, use the set() constructor:

>>> type(set())
<type 'set'>

Adding and removing items

Use set.add() to add an item to the set:

>>> set3 = {37, 51, 42, 60}
>>> set3.add(98)
>>> set3
{98, 37, 42, 51, 60}

…and use set.remove() to remove an item:

>>> set3.remove(51)
>>> set3
{98, 37, 42, 60}

Set operations

Sets have special methods to perform boolean operations with other sets.

Union

The union operation returns a new set with elements from both sets:

>>> set1 = {1, 2, 3, 4}
>>> set2 = {8, 1, 4, 5, 6}
>>> set1.union(set2)
{1, 2, 3, 4, 5, 6, 8}

Intersection

The intersection operation returns a new set with elements which are common to both sets:

>>> set1.intersection(set2)
{1, 4}

Difference

The difference operation returns a new set with elements which are in the first set and not in the second:

>>> set1.difference(set2)
{2, 3}
>>> set2.difference(set1)
{8, 5, 6}

Symmetric difference

Symmetric difference corresponds to the xor operator in boolean logic. It returns a list of items which are in either one set or another, but not in both.

>>> set2.symmetric_difference(set1)
{2, 3, 5, 6, 8}

For the difference operation, the order of the sets matters. For the other operations, changing the order will not change the result.

Last edited on 01/09/2021