Signup/Sign In
LAST UPDATED: OCTOBER 14, 2021

Set in Python with Examples

    There are three essential data structures in the Python language: list, tuple and dictionary. In addition to these, inspired by other data structures, there are various other objects, one of them is SET.

    A set object helps store unique items in an unordered fashion. These elements are hashable. Being hashable refers to an object which possesses a hash value (that doesn't change during its lifetime). The elements stored in a set can be of different data types (integer, string, float, tuple) and it can store any number of elements.

    Features of a set:

    1. Every element should be unique

    2. Every element is immutable (i.e it can't be changed once it has been defined). It can't have list elements, dictionary elements or set elements.

    3. It is iterable.

    But in the entirety, the set is mutable, which means data elements can be added or removed from it.

    Why use set instead of lists?

    The advantage of using a set object includes that it has a highly optimized way of searching for specific elements in it. It can be understood as an object which is based on hash table data structure, and hash tables, as you might know, is an efficient data structure for fast searching.


    So How do I create a set?

    It can be created in 2 ways:

    1. Using the set() method:

    When a set is created using the set() method, only the unique elements are added to the set, even though the same element is defined twice inside the set() function. This is because the basic rule of defining a set says that elements have to be unique.

    my_set = set([1,2,3,2, 'a', 'b', 'a'])
    print(my_set)

    Output:

    {1, 2, 3, 'b', 'a'}

    2. Using curly braces and comma-separated values

    A set can have multiple types of data in it. Below is an example that shows set with a single data type. It is followed by an example that shows a set being defined with elements of different data types.

    my_first_set = {1, 2, 3}  # Has a single data type
    print(my_first_set)

    Output:

    {1,2,3}

    Elements of different data types can be declared inside the set object. See the example below:

    my_first_set = {1, 2, 3, 'a', "Studytonight", (4.56)}   # Can have multiple data types
    print(my_first_set)

    Output:

    {1, 2, 3, 4.56, 'Studytonight', 'a'}
    

    3. Creating an empty set

    You can create an empty set using the set() method without any values provided to it as argument.

    my_first_set = set()
    print(type(my_first_set))

    Output:

    <class 'set'>


    Some useful operations/methods for Set:

    Below we have covered some useful operations and methods for set data structure.

    1. Adding more elements to a set

    We can add more elements to a set using the add() function, for example:

    my_first_set = {1,2,3,'a'}
    my_first_set.add('b')
    print(my_first_set)

    Output:

    {1, 2, 3, 'b', 'a'}


    2. Union of two sets

    Union of two set or in simple words two different sets can be joined together using the union() method or the | operator.

    Using the union() method:

    It combines two sets together and returns the resultant set.

    Following is the syntax for using the union() function:

    first_set_name.union(second_set_name)

    Let's take an example:

    set_one = {1,2,3,4}
    set_two = {'One','Two','Three','Four'}
    union_of_two_sets = set_one.union(set_two)
    print(union_of_two_sets)

    Output:

    {1, 2, 3, 4, 'Four', 'One', 'Three', 'Two'}

    Using | operator:

    Following is the syntax to use the | operator:

    first_set_name | second_set_name

    Let's take an example:

    set_one = {1,2,3,4}
    set_two = {'One','Two','Three','Four'}
    union_of_two_sets = set_one|set_two
    print(union_of_two_sets)

    Output:

    {1, 2, 3, 4, 'Four', 'One', 'Three', 'Two'}


    3. The intersection of two sets

    It finds out the common values between two sets and returns those values as a resultant set. It can be performed using the intersection() method or the & operator.

    Using the intersection() method:

    Following is the syntax of the intersection() method:

    first_set_name.intersection(second_set_name)

    It returns an empty set if no 2 elements are common in the two sets.

    Let's take an example:

    set_one = {1,2,3,4, 'Five', 5}
    set_two = {'One','Two','Three','Four','Five', 5}
    intersection_of_two_sets = set_one.intersection(set_two)
    print(intersection_of_two_sets)

    Output:

    {'Five', 5}

    Using the & operator:

    Following is the syntax of the & operator:

    first_set_name & second_set_name

    Let's take an example:

    set_one = {1,2,3,4, 'Five', 5}
    set_two = {'One','Two','Three','Four','Five', 5}
    intersection_of_two_sets = set_one&set_two
    print(intersection_of_two_sets)

    Output:

    {'Five', 5}


    4. Find the Difference between two sets

    It displays all elements which are in the first set but not in the second set. This can also be achieved in two ways:

    Using the difference() method:

    Following is the syntax for the difference() method:

    first_set_name.difference(second_set_name)

    Let's take an example:

    set_one = {1,2,3,4, 'Five', 5}
    set_two = {'One','Two','Three','Four','Five', 5}
    difference_of_two_sets = set_one.difference(set_two)
    print(difference_of_two_sets)

    Output:

    {1, 2, 3, 4}

    Using the - operator:

    Following is the syntax to use - operator

    first_set_name - second_set_name

    Let's take an example:

    set_one = {1,2,3,4, 'Five', 5}
    set_two = {'One','Two','Three','Four','Five', 5}
    difference_of_two_sets = set_one - set_two
    print(difference_of_two_sets)

    Output:

    {1, 2, 3, 4}


    5. Deleting elements from a set

    When we talk about deleting, two different aspects come into the picture, first is deleting the entire set or the second, which is deleting a specific element/elements from the set. Let us see both.

    Removing specific element/elements:

    Specific elements can be removed either using the discard() function or remove() function.

    Using the discard() function:

    This function's parameter is the element which needs to be deleted. Here, if the element doesn't even exist in the set, the set remains unchanged and no exception is raised.

    Let's take an example:

    my_first_set = {1, 3, 5, 6, 0, 9}
    print(my_first_set)
    my_first_set.discard(9)
    print(my_first_set)

    Output:

    {1, 3, 5, 6, 0}

    Using the remove() function:

    This function takes the element to be deleted as the parameter. Here, if the element that has been specified as a parameter doesn't exist, it raises a KeyError. After the remove function eliminates the specific element, the function internally sorts the elements in the ascending order and it is then displayed.

    Let's take an example:

    my_first_set = {1, 3, 5, 7, 0, 6}
    my_set.remove(6)
    print(my_first_set)

    Output:

    {0, 1, 3, 5, 6, 7}
    

    Using pop() function:

    Since a set is unordered, an element is randomly deleted when we use the pop() function hence no parameter needs to be passed to the this function.

    my_first_set = {1,2,3,'a'}
    my_first_set.pop()
    print(my_first_set)

    Output:

    {2, 3, 'a'}

    Removing the entire set using clear() function:

    This can be done using the clear() function. It clears or empties the entire set by deleting all the elements of the set. It displays an empty set since all the elements have been deleted.

    Following is the syntax of clear() method:

    set_name.clear()

    Let's take an example:

    set_one = {1,2,3,4, 'Five', 5}
    set_one.clear()
    print(set_one)

    Output:

    set()
    


    Some more Set Operators and Operations:

    In the table below we have specified some more operations and operators for a set data structure. For the operator/operation below, consider that we have two sets with name set_one and set_two:

    Operator/Operation Description
    key in set_one checks if an element is present in set_one
    key not in set_one checks for the absence of an element in set_one
    set_one == set_two checks if set_one is equivalent to set_two
    set_one != set_two checks if set_one is not equivalent to set_two
    set_one <= set_two set_one is a subset of set_two
    set_one < set_two set_one is a proper subset of set_two
    set_one >= set_two set_one is a superset of set_two
    set_one > set_two set_one is proper superset of set_two
    set_one | set_two union of set_one and set_two
    set_one & set_two intersection of set_one and set_two
    set_one - set_two the difference, i.e elements in set_one but not set_two
    set_one ^ set_two elements in precisely one of set_one or set_two, but not both

    Now let's take an example to see the implementation of these operators:

    Try playing around with the set_one and set_two values using different operators to see how things change.


    Disadvantages of using a Set:

    1. The elements in a set are unordered, i.e. they don't maintain any order. They are arbitrary.

    2. Data which is immutable can be added to a set because once added data cannot be changed.

    You may also like:

    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS