Sets are a special kind of unorderered collection which contains only unique elements, and has special methods to perform set operations like union, intersection, difference etc.

Set basics

Sets can be created from a list or tuple using the set constructor. Notice how all duplicated items are removed, and appear only once int the resulting set:

set1 = set([1, 3, 2, 3, 4, 3])
>>> set([1, 2, 3, 4])

New syntax for creating sets

Since Python 2.7, non-empty sets can be created by enclosing a sequence of comma-separated values in curly brackets:

set2 = {1, 8, 4, 5, 6}
>>> set([8, 1, 4, 5, 6])

Curly brackets are also used to create dictionaries. So a pair of empty curly brackets will create a dictionary, not a set:

>>> <type 'dict'>

To create an empty set, it is still required to use the set constructor:

>>> <type 'set'>

Adding and removing set items

set3 = {37, 51, 42, 60}

set([98, 42, 51, 60, 37])

set3.remove(51) print(set3) set([98, 42, 60, 37])


s.add(x) add element x to set s s.remove(x)

Set operations

Sets have methods to perform boolean operations with other sets: union, difference and intersection.

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

>>> set([1, 2, 3, 4])
>>> set([8, 1, 4, 5, 6])
>>> set([1, 2, 3, 4, 5, 6, 8])

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

>>> set([1, 4])

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

>>> set([2, 3])
>>> set([8, 5, 6])

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 23/01/2018