Sets

Sets are unordered data types, and they can contain unique elements only. Also, there is no indexing, so we cannot access sets using indices.

Since they can contain unique elements only, there can be only one representation of the same object. Sets are created using the curly brackets – { }.

my_set={1,2,3}
print(my_set)

Our set gets printed out –

{1, 2, 3}

Adding, Removing and Clearing a Set

We cannot change items in a set, but we can add them using the add() method as follows –

my_set.add(4)
my_set.add(1)

When we run it, we see that only 4 has been added. This is because 1 already exists in our set.

{1, 2, 3, 4}

We can remove an item from our set by using either the remove() method or the discard() method. Personally, I prefer the remove() method.

my_set.remove(1)
my_set.discard(3)
print(my_set)

When we run the above code, our remaining set gets printed out-

{2, 4}

Now let’s destroy my_set completely! Lol, just joking. We are going to delete all the remaining elements, and NOT delete the entire set. Note that we will still be able to add elements to it. The clear() method is used to do this-

my_set.clear()
print(my_set)

And we get this-

set()

Length of a Set

Let’s take the original my_set, with three elements -1, 2, 3. We find it’s length using the len() funtion.

my_set={1,2,3}
print(len(my_set))

We get the length as 3.

set() constructor

If we ever want to convert a list or tuple or any other plausible data type directly to a set, we will use the set() constructor as follows-

my_list=[1,1,1,2,3,4]
my_set=set(my_list)
print(my_set)

And our list gets converted to a set and printed out. Note that the extra 1’s will be removed-

{1, 2, 3, 4}

We will look upon some other methods of sets later on, which will help us a lot.

Sets