SetsΒΆ

Sets are Python objects similar to lists. The main difference is that Python sets, similarly to the mathematical objects, contain only one copy of each element.

Here is how sets are defined:

In [1]:
s1 = {131, 2, 23, 4}

The set s1 will contain just one copy of each element:

In [2]:
s1
Out[2]:
{2, 4, 23, 131}

The elements in the set won't necessarily be in any particular order. We can check whether an element is in the set like this:

In [3]:
4 in s1
Out[3]:
True
In [4]:
120 in s1
Out[4]:
False

A set can contain any immutable object:

In [5]:
{1, "hi", "EngSci", 100}
Out[5]:
{1, 100, 'EngSci', 'hi'}

We can get a set of all the element in a list like this:

In [6]:
L = [1, 2, 10, 1, 2, 2, 5]
set(L)
Out[6]:
{1, 2, 5, 10}

Finally, we can iterate through a set like this:

In [7]:
for e in {2, 4, 23, 131}:
    print(e)
2
131
4
23

The main use that we'll see of sets is going through every element in a list without repetition:

In [8]:
for e in set([4, 5, 4, 5, 4, 5, 7, 10]):
    print(e)
10
4
5
7