The 'Set'data structure in python

The 'Set'data structure in python

Set is an in-built python data structure. You can store integers, floats, booleans, and strings in a set.

Example of a set:

store={2,True, 3.14 , 'hello'}

Important: A set in python does not store duplicates. And this is why it is an important data structure in computer science. Elements in the set are not in the order you assign them.

Adding an element to a set:

We use 'add()' method to add an element to a set.

store.add(3)

If we add an element to a set, which is already present in the set, then it ignores that element and keeps the original element in it.

Check if a given element is in the set or not:

use 'in' keyword to check the element is present in the set:

print(  3 in store )

output: true or False

you can also check if the element is not in the set:

print(  3 not in store )
output: True or False

Other important operations on set:

To remove an element from a set use 'remove()' method:


store.remove(3)

We can get the length of the set by using 'len()' function.


len(store)

Important: We know that we will get an error if we try to remove an element from the set if that particular element is not present in the set.

But you can use the 'discard()' method to remove the element from the set if it is present in the set, else do nothing.

This method will save our program from getting errors.

Storing a group of elements directly into the set:


store2 = set( [ 21, True, 13.14 , 'Hi' ] )

Clear all elements from a set with one method :

store.clear()

Since they are sets, we can perform union and intersection operations with the sets:

Intersection:

set1.intersection(set2) 
# intersection means: it is the collection of common elements from both the sets.

Union:

set1.union(set2)
# union means: it is the collection of all elements from both sets.