Sobes.tech
Junior

What are sets used for in Python?

sobes.tech AI

Answer from AI

Sets in Python are used to store unique, unordered elements.

Main applications:

  • Removing duplicates: Easily obtain a set of unique elements from a list or tuple.

    # Example of removing duplicates
    my_list = [1, 2, 2, 3, 4, 4, 5]
    unique_elements = set(my_list)
    # unique_elements is now {1, 2, 3, 4, 5}
    
  • Membership testing: Very efficient membership check in a set (average complexity O(1)).

    # Example of membership check
    my_set = {1, 2, 3}
    print(5 in my_set)
    # Output: False
    
  • Set operations: Union, intersection, difference, symmetric difference.

    Operation Method/operator Description Example ({1, 2}, {2, 3}) Result
    Union union() / ` ` Elements from both sets `{1, 2}
    Intersection intersection() / & Common elements {1, 2} & {2, 3} {2}
    Difference difference() / - Elements of first set not in second {1, 2} - {2, 3} {1}
    Symmetric difference symmetric_difference() / ^ Elements not common to both {1, 2} ^ {2, 3} {1, 3}
  • Fast comparison: Equality, subset, superset.

    # Examples of comparison
    set1 = {1, 2, 3}
    set2 = {1, 2}
    print(set2.issubset(set1)) # Check if set2 is subset of set1
    # Output: True
    

Sets are ideal when element order does not matter, and high performance is needed for membership testing and duplicate removal.