A set is an unordered collection of unique items. It can be defined in two different manners:

As a sidenote, the empty set must be built with set() since Python interprets {} as an empty dictionary.

Operators and methods

Sets support the already familiar x in set, len(set), and for x in set. Since sets are unordered, there is no way to record the position of an element and thus indexing or slicing is not possible.

The set type is mutable in such a way that its contents can be changed using methods like add() and remove().

The Python translation of fundamental operations is pretty undisguised. Let’s consider the following sets,

s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}

and we’ll take a look at some of the most usual. For a complete outlook refer to the Python documentation. In all cases we have an operator and a method available which return a new set and are in essence equivalent.

Víctor Adell
Universitat Politècnica de Catalunya, 2019

Prohibit copiar. Tots els drets reservats.
No copy allowed. All rights reserved.