Online-Academy
Look, Read, Understand, Apply

Set

Set

A set in Python is a data structure, it is an unordered, mutable (changeable) collection of unique elements. It is mainly used when we have to store values without duplicates and perform mathematical set, simply no duplicates.

When to Use a Set?
  • Removing duplicate values
  • Fast membership testing
  • Mathematical operations (union, intersection, etc.)
  • Comparing collections
Creating Sets
    # Set is created using curly braces, elements are written inside cruly braces
    numbers = {1, 2, 3, 4}

    # Set can be created Using set() function also
    letters = set(['a', 'b', 'c'])

    # Empty set (must use set(), not {})
    empty_set = set()

Key Characteristics of Sets

  • Unordered (no indexing)
  • No duplicate elements
  • Mutable (can add or remove elements)
  • Can store different data types
  • Elements must be immutable (no lists or dictionaries)

Accessing elements of set, elements cannot be accessed by index, but can be accessed using loop.

    for item in s:
        print(item)

Adding element to set

s = {1, 2}
s.add(3)
print(s)
s.update([4, 5, 6])
print(s)
#remove method is used to remove element of set, if element is not found, error will be given.    
s.remove(2)
# discard method removes elements, no error is given even element is not found. s.discard(10)
# pop method removes and returns a ramdom element from a set.    
x = s.pop()
print(x)
# clear mehtod is used to clear a set
s.clear()
# To copy content of one set to another set copy method is used. 
s1 = {1, 2, 3}
s2 = s1.copy()
    
Set operations
# taking union of two sets, we can use union method or | operator a = {1, 2, 3} b = {3, 4, 5} print(a.union(b)) print(a | b) # To perform set intersection, we can use intersection method or & operator print(a.intersection(b)) print(a & b) # To perform set difference, we can use difference method or - operator print(a.difference(b)) print(a - b) # Symmetric difference: To get Elements present in either set but not both. print(a.symmetric_difference(b)) print(a ^ b) # To getting subset: issubset method is used a = {1, 2} b = {1, 2, 3} print(a.issubset(b)) # To check if a set is superset: issuperset method is used. print(b.issuperset(a)) # To check if sets are disjoint: isdisjoint method is used. x = {1, 2} y = {3, 4} print(x.isdisjoint(y)) # To check set membership: in operator is used. s = {1, 2, 3} print(2 in s) # True print(5 not in s) # Set comprehension squares = {x*x for x in range(1, 6)} print(squares)