Sets and Set Methods

Introduction to Sets

  • Unordered, Unique, Mutable collection of items separated by comma , enclosed in {}
  • Used to lookup larger data
  • We can perform set operations like union, intersection, difference, etc.
  • Can store only immutable data types
  • Doesn't store duplicates, if duplicates are added, only one instance is stored
  • Indexing and position related function are invalid since it is unordered
  • Example: {1, 2, 3}, {"apple", "banana", "orange"}, {1, "hello", (1, 2)}

Creating Sets

    Examples:
    1. my_set = {1, 2, 2, 3} print(my_set) # {1, 2, 3} (duplicates are removed) my_set = {1, "hello", (1, 2)} print(my_set) # {1, "hello", (1, 2)} my_set = {1, [2, 3]} # Raises TypeError since list is mutable my_set = {"apple", "banana", "orange"} print(my_set) # {'banana', 'orange', 'apple'} (unordered)

Set Methods

  • Functions that perform operations on sets and return a new set or modify the existing
  • Data Related Operations: add(), update(), remove(), discard(), pop()
  • Numeric Function: sum(), min(), max(), len()
  • General: sorted(), copy()
  • Set Operations: union, intersection, difference, symmetric_difference

add

  • Used to add an element to a set
  • Syntax: set_name.add(element)
  • Examples:
    1. my_set = {1, 2, 3} my_set.add(4) print(my_set) # {1, 2, 3, 4} my_set.add(2) print(my_set) # {1, 2, 3, 4} (adding duplicate doesn't change the set) my_set.add([5, 6]) # Raises TypeError since list is mutable

update

  • For adding multiple elements to a set from an iterable (list, tuple, etc) like extend of list
  • Syntax: set_name.update(iterable)
  • Examples:
    1. my_set = {1, 2, 3} my_set.update([4, 5]) print(my_set) # {1, 2, 3, 4, 5} my_set.update((6, 7)) print(my_set) # {1, 2, 3, 4, 5, 6, 7} my_set.update({8, 9}) print(my_set) # {1, 2, 3, 4, 5, 6, 7, 8, 9} my_set.update("hello") print(my_set) # {1, 2, 3, 4, 5, 6, 7, 'h', 'e', 'l', 'o'} (string is treated as an iterable of characters)

remove and discard

  • Used to remove an element from a set
  • remove() gives error if the element is not found but discard() does not
  • Syntax: set_name.remove(element); set_name.discard(element)
  • Examples:
    1. my_set = {1, 2, 3, 4} my_set.remove(2) print(my_set) # {1, 3, 4} my_set.remove(5) # Raises KeyError since element is not found my_set.discard(3) print(my_set) # {1, 4} my_set.discard(5) # No error raised even though element is not found print(my_set) # {1, 4}

pop

  • Used to remove and return an arbitrary element from a set
  • Syntax: set_name.pop()
  • Examples:
    1. my_set = {1, 2, 3, 4} removed_element = my_set.pop() print(removed_element) # Could be any element from the set print(my_set) # Set with one less element

Numeric Functions

  • Used to perform numeric operations on sets containing numbers
  • Valid Functions: sum (only for int and float sets), min, max, len
  • Examples:
    1. num_set = {1, 2, 3, 4, 5} print(sum(num_set)) # 15 print(min(num_set)) # 1 print(max(num_set)) # 5 print(len(num_set)) # 5

Sorted

  • Used to sort the elements of a set in ascending order by default
  • sorted() function is used since sort() method modifies in-place
  • Examples:
    1. my_set = {3, 1, 4, 2} sorted_set = sorted(my_set) print(sorted_set) # [1, 2, 3, 4] print(my_set) # {1, 2, 3, 4} (original set remains unchanged) str_set = {"apple", "ball", "cat"} sorted_str_set = sorted(str_set, reverse=True) print(sorted_str_set) # ['cat', 'ball', 'apple'] (sort in descending order) sorted_str_set = sorted(str_set, key=len) print(sorted_str_set) # ['ball', 'cat', 'apple'] (sort by length of strings)

Copying Sets

  • Used to create a copy of a set to avoid modifying the original set
  • Examples:
    1. original_set = {1, 2, 3} copied_set = original_set copied_set.add(4) print(original_set) # {1, 2, 3} print(copied_set) # {1, 2, 3} another_copy = original_set.copy() another_copy.add(5) print(original_set) # {1, 2, 3} print(another_copy) # {1, 2, 3, 5}`

Set Operations

  • Used to perform mathematical set operations like union, intersection, difference, etc.
  • Valid Functions: union, intersection, difference, symmetric_difference
  • Examples:
    1. set_a = {1, 2, 3} set_b = {3, 4, 5} print(set_a.union(set_b)) # {1, 2, 3, 4, 5} or set_a | set_b print(set_a.intersection(set_b)) # {3} or set_a & set_b print(set_a.difference(set_b)) # {1, 2} or set_a - set_b print(set_a.symmetric_difference(set_b)) # {1, 2, 4, 5} or set_a ^ set_b

Frozenset

  • Immutable version of a set, created using frozenset() function
  • Once created, elements cannot be added or removed
  • Examples:
    1. my_frozenset = frozenset([1, 2, 3]) print(my_frozenset) # frozenset({1, 2, 3}) my_frozenset.add(4) # Raises AttributeError since frozenset is immutable print(my_frozenset) # frozenset({1, 2, 3})