Quick Enquiry Form

×

    Sets in Python

    sets-in-python
    Blog

    Sets in Python

    Introduction of Sets in Python

    A Set is a collection of unordered data types that can be iterated, mutated, and do not contain any duplicate components. The set class in Python demonstrates the mathematical concept of a set. The primary benefit of using a set over a list is that it has a highly advanced method for determining if a particular component is in the set. Hash tables are the foundation for this system. Items in sets cannot be accessed via indexes, as they are not ordered as in lists.

    Features of the Sets in Python

    In Python, a set is a predefined data structure with the three properties listed below.

    • Unordered
    • Unchangeable
    • Unique

    Unordered

    The sets do not retain the order in which the elements were added to the set, in contrast to the lists. Whenever the set object is accessed, the items will always be arranged in a different order than before. As a result, each element in the set does not have an index value. 

    Unchangeable

    Items in a set must be unaltered once they are created. Set items could not be changed which means the values of items in the set could not be modified. However, any number of items could be added or removed from the Set. A set can be changed, but the elements within it need to be of an unchangeable/immutable type.

    Unique

    There can never be more than one item in the set with the same value.

    Also, the sets are heterogeneous in nature such that it contains strings, integers, and booleans values. The sets in python include all types of data.

    Creation of a set in Python

    A set is formed by enclosing all the items/elements inside a pair of curly braces or by using the set() function.

    Illustration

    Months={“Jan”,”Feb”,”Mar”}

    Seasons={“Summer”.”Winter”,”Spring”,Autumn”}

    Dates={15,14,19}

    print(Months)

    print(Seasons)

    print(Dates)

    Output

    After the execution of the above code, the result will be produced. It is to be noted that the order of the items/elements in the set is not the same and has changed.

    set([‘Jan’, ‘Mar’, ‘Feb’])

    set([“Autumn”, “Summer”,” Spring”,” winter”])

    set([14,19,15])

    Accessing The Values in a Set in Python

    Individual values inside the set cannot be accessed. Rather, all the elements of the set can be accessed together. However, by means of looping through the set, individual elements’ lists can be obtained.

    Illustration

    Seasons=set([“Autumn”,”Summer”,”Winter”,”Spring”])

    for s in Seasons:

    print(s)

    Output

    The below output is obtained on the execution of the above code:

    Summer

    Autumn

    Spring

    Winter

    Addition of Items to a Set

    Elements to the set can be added by means of using add() function. No specific index is attached to the recently added element.

    Illustration

    Dates =set([“12″,”13″,”16″,”22″,”30″,”27”])

    Dates.add(“18”)

    print(Dates)

    Output

    The following result is obtained on thexecution of the “add” code

    set([’12’, ’16’, ’13’, ’22’, ’18’, ’30’, ’27’])

    Removing Item from a Set

    Any element from the set can be removed by deploying the discard() or remove() method. Similar to add method. no specific index is used here, as elements of the set are not indexed.

    Illustration

    Directions=set([“East”,”West”,”South”,”North”])

    Directions.discard(“West”)

    print(Directions)

    Output

    The below result is obtained by means of code execution 

    set([‘East’, ‘North’, ‘South’])

    Set Operations in Python

    The sets in Python are commonly used for mathematical operations such as 

    • Union, 
    • Intersection, 
    • Difference, and 
    • Comparison, among others.

    It is possible to create a set, access its components, and perform the above-mentioned mathematical operations.

    Union of Sets in Python

    In the sets in python, all the unique elements from the two sets can be combined into a single set on the execution of the Union operation of two sets. The common element in both sets here is number 17

    Illustration

    Num_set A = set([“18″,”3″,”17”])

    Num_set B = set([“5″,”7″,”9″,”17″,”13”])

    All Num_set = Num_setA|Num_setB

    print(AllNum_set)

    Output

    The operation union of sets gives out the below result, where it is to note that the number 17 is included only once in the resultant set in python.

    set([‘5′, ’18’, ’17’, ‘3’, ‘9’, ‘7’. ‘13’])

    Intersection of Sets in Python

    The common element in both sets will be included in the resultant set on the application of intersection operation to the two sets. Be noted that the element “Mon” is available in both the sets below.

    Illustration

    DaysA = set([“Mon”,”Thu”,”Wed”])

    DaysB = set([“Mon”,”Tue”,”Fri”,”Sun”,”Sat”])

    AllDays = DaysA & DaysB

    print(AllDays)

    Output

    On the execution of Intersection Operation, the below is obtained resultantly, as Mon is common in both sets.

    set([‘Mon’]) 

    Difference of Sets in Python

    A difference operation on two sets yields A new set that includes only entries from the first set and nothing from the second. The item “March” is available in both of the sets in the illustration below, and hence it will not be observed in the resultant set.

    Illustration

    MonthsA = set([“Jan”,”Feb”,”March”])

    DaysB = set([“Feb”,”March”,”August”,”November”,”September”])

    Allmonths = MonthsA – MonthsB

    print(AllMonths)

    Output

    On execution of the difference of set operation, the new set produced does not include the month “March” as it is present in both the sets, and no element from the second set is found.

    set([‘Jan’, ‘Feb’])

    Compare Sets in Python

    It is possible to determine whether a particular set is a subsection or superset of another set. A True or False result is determined by the presence of elements within the sets.

    Illustration

    MonthsA = set([“Jan”,”June”,”July”])

    MonthsB = set([“Jan”,”Feb”,”April”,”June”,””,”July”,”September”])

    SubsetRes = MonthsA <= MonthsB

    SupersetRes = MonthsB >= MonthsA

    print(SubsetRes)

    print(SupersetRes)

    Output

    On execution of the Campare Operation, in sets, the following result is obtained

    True

    Frozen Sets in Python

    A Frozenset is a class that has the properties of a set, but once its components have been assigned, those components are frozen and cannot be modified. Tuples and frozen sets can be viewed as immutable lists and sets, respectively.

    Illustration

    A = frozenset([2, 4, 6 , 4, 8, 10])

    B = frozenset([3, 5, 7, 9, 11, 13])

    print(A)

    print(B)

    This will result in:

    frozenset({2, 4, 6, 8, 10, 12})

    frozenset({3, 5, 7, 9, 11, 13})

    Set Methods in Python

    Some of the most frequently used Python set methods that have not yet covered will be discussed below.

    copy()

    This method gives you a duplicate of the given set.

    Illustration

    string_set = {“Nimme”, “Mike”, “Johny”, “Mark”}

    A = string_set.copy()

    print(A)

    The output denotes that A is a copy of the set string_set:{‘Johny’, ‘Mike’, ‘Nimmi’, ‘Mark’}

    isdisjoint()

    This technique checks to see if the two sets in statement have an intersection. If there are no common items between the sets, this method reports True; or else, it reports False.

    Illustration

    Months_A = {“Jan”, “Feb”, “April”, “May”}

    Months_B = {“June”, “July”, “March”, “September”}

    C = Months_A.isdisjoint(Months_B)

    print(C)

    Since there is no items common in the two sets, the output is 

    True

    len()

    If you want to know the number of items in a set, you can use this method to get it.

    Illustration

    Months A = {“January,” “March,” “May,” and “August”}

    print(len(Months A))

    The output indicates length of the set as following

    4

    Conclusion

    Detailed explanations of sets in Python are provided in this guide. Both the mathematical and Pythonic definitions of sets are identical. The simplest definition of a set is that it is a group of unordered components. Even though the set can be changed(mutable), the items within it cannot. However, it is possible to add and remove items from a set arbitrarily. Elements are typically indexed in the vast majority of data structures. Set elements, on the other hand, really aren’t indexed. This prevents us from performing operations that focus on a particular set of components.

    python-training-in-chennai

    100% Placement Support

    Live Online & Classroom
    Python Programming

    Discover your best career by learning on-demand Python Programming

    data-science-training-in-chennai

    Real Time Hands-on Training

    Live Online & Classroom
    Data Science Training

    Our training course will give you the required skills..

    machine learning in chennai

    Learn From Industry Experts

    Live Online & Classroom
    Machine Learning Training

    Machine learning is one of the buzzwords recently and this can be attributed…

    rpa-training-in-chennai

    No Cost EMI Option

    Live Online & Classroom
    RPA Training

    Discover your best career by learning on-demand RPA technology…

    software-testing-in-chennai

    Value-Based Certification

    Live Online & Classroom
    Software Testing Course

    Want to get career-oriented Software Testing Training in Chennai Then think about SLA Institute…

    java-training-in-chennai

    Lifetime Career Guidance

    Live Online & Classroom
    Java Training

    Our training course will give you the required skills to be one of the best picks by the IT employers…

    selenium-training-in-chennai

    Flexible Learning Hours

    Live Online & Classroom
    Selenium Testing

    Our training course will give you the required skills to be one of the best picks by the IT employers…

    dotnet-training-in-chennai

    Convenient Training Modes

    Live Online & Classroom
    Dot Net Training

    Discover the great opportunities in Dot Net by practicing on real-life implementation strategies for delivering…

    ccna-training-in-chennai

    Convenient Training Modes

    Live Online & Classroom
    CCNA Training

    The CCNA certification helps you in becoming a sound, well-equipped network engineer…

    php-course-in-chennai

    Advanced Course Curriculum

    Live Online & Classroom
    PHP Training

    Being a language for general purposes, PHP can develop both static and dynamic websites…

    full-stack-developer-training

    Experiential Full Stack Course

    Live Online & Classroom
    Full Stack Development

    Learn Full Stack Developer course from SLA Institute…

    1
    Softlogic-Academy