Python : Sets

Sets are unordered collections of unique elements. They are particularly useful when you need to store a collection of distinct items and perform set operations like union, intersection, difference, and so on. Here's an overview of Python sets:

Creating a Set


You can create a set by enclosing elements within curly braces `{}`.


my_set = {1, 2, 3, 4, 5}
 

Alternatively, you can use the `set()` function to create a set from an iterable (like a list or tuple).


my_set = set([1, 2, 3, 4, 5])
 

Set Elements


Sets contain only unique elements. If you try to add duplicate elements, they will be ignored.


my_set = {1, 2, 3, 4, 5, 1}  # Duplicate 1 will be ignored
print(my_set)  # Output: {1, 2, 3, 4, 5}

 

 Accessing Elements


Since sets are unordered, they do not support indexing or slicing like lists or tuples. You can, however, check for membership using the `in` operator.


print(3 in my_set)  # Output: True
 

Set Operations


Sets support various mathematical set operations such as union, intersection, difference, and symmetric difference.

  •  Union ( | or union() )   : Combines elements from two sets, excluding duplicates.
  •  Intersection ( & or intersection()`)   : Finds common elements between two sets.
  •  Difference ( - or difference() )   : Finds elements present in the first set but not in the  second set.
  •  Symmetric Difference ( ^ or symmetric_difference() ) : Finds elements that are in either of the sets, but not in both.


set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1 | set2
intersection_set = set1 & set2
difference_set = set1 - set2
symmetric_difference_set = set1 ^ set2

print(union_set)  # Output: {1, 2, 3, 4, 5}
print(intersection_set)  # Output: {3}
print(difference_set)  # Output: {1, 2}
print(symmetric_difference_set)  # Output: {1, 2, 4, 5}

 

Set Methods


Sets have various built-in methods for performing common operations like adding elements, removing elements, and checking subsets.

  • add()            : Adds an element to the set.
  • remove()      : Removes a specified element from the set (raises an error if the element is not present).
  • discard()      : Removes a specified element from the set (does nothing if the element is not present).
  • pop()            : Removes and returns an arbitrary element from the set.
  • clear()          : Removes all elements from the set.
  • issubset()    : Checks whether the set is a subset of another set.
  • issuperset() : Checks whether the set is a superset of another set.
  • copy()           : Returns a shallow copy of the set.

Frozen Sets


Python also has another type of set called frozen sets. Frozen sets are immutable and can be created using the frozenset() function.


frozen_set = frozenset([1, 2, 3])
 

Frozen sets support all set methods that don't modify the set (e.g., union(), intersection(), difference(), etc.).

Sets are a powerful tool for various operations involving collections of unique elements.