Python Sets

A set in Python is an in-built data structure which is a collection of unique elements without any particular order. Sets are highly useful for operations involving membership testing, removing duplicates, or doing mathematical set operations like union, intersection, and difference.

Some Key Properties of Sets

  1. Unordered:
  • The cardinality of a Set is not introspective. {1, 2, 3} is equal to {3, 1, 2}. This is because since it does not maintain ordering, you cannot index or slice it as with lists.


2. Unique Elements:

  • In a set, duplicate elements are removed automatically. For instance, {1, 2, 2, 3} will become {1, 2, 3}.


3. Mutable:

  • Sets are mutable objects; that is, you can add or remove elements. But you can’t add mutable elements like lists, etc- the elements of a set must be immutable objects, like numbers, strings, and tuples.

4. Unhashable Elements Not Allowed:

  • Since a set uses hashing, all of its elements must be hashable. This means that you won’t be able to have lists or dictionaries as elements of the set.

Creating Sets

  1. Using Curly Braces:
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}

2. Using the set() Constructor:

my_set = set([1, 2, 3, 4, 4])
print(my_set) # Output: {1, 2, 3, 4}

3. Empty Set:

  • Use set() to create an empty set. Using {} creates an empty dictionary instead.
empty_set = set()
print(type(empty_set)) # Output:

Common Set Methods

  1. Adding Elements:
  • Use add() to add a single element.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

2. Updating with Multiple Elements:

  • Use update() to add multiple elements from an iterable (e.g., list, tuple).
my_set = {1, 2}
my_set.update([3, 4, 5])
print(my_set) # Output: {1, 2, 3, 4, 5}

3. Removing Elements:

  • remove(): Removes a specified element. Raises an error if the element is not found.
  • discard(): Removes a specified element. Does not raise an error if the element is not found.
  • pop(): Removes and returns an arbitrary element.
  • clear(): Removes all elements.
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}

my_set.discard(4) # No error even if 4 is not present
print(my_set) # Output: {1, 3}

4. Checking Membership:

  • Use the in and not in operators.
print(2 in {1, 2, 3}) # Output: True
print(4 not in {1, 2, 3}) # Output: True

Mathematical Set Operations

  1. Union (| or union()): Combines elements from both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Output: {1, 2, 3, 4, 5}
print(a.union(b)) # Output: {1, 2, 3, 4, 5}

2. Intersection (& or intersection()): Returns elements common to both sets.

print(a & b) # Output: {3}
print(a.intersection(b)) # Output: {3}

3. Difference (- or difference()): Returns elements in one set but not the other.

print(a - b) # Output: {1, 2}
print(a.difference(b)) # Output: {1, 2}

4. Symmetric Difference (^ or symmetric_difference()): Returns elements in either set, but not in both.

print(a ^ b) # Output: {1, 2, 4, 5}
print(a.symmetric_difference(b)) # Output: {1, 2, 4, 5}

Other Useful Methods

  1. issubset(): Checks if a set is a subset of another.
print({1, 2}.issubset({1, 2, 3})) # Output: True

2. issuperset(): Checks if a set is a superset of another.

print({1, 2, 3}.issuperset({1, 2})) # Output: True

3. isdisjoint(): Checks if two sets have no elements in common.

print({1, 2}.isdisjoint({3, 4})) # Output: True

Applications of Sets

  1. Removing Duplicates:
my_list = [1, 2, 2, 3, 4, 4]
unique_elements = set(my_list)
print(unique_elements) # Output: {1, 2, 3, 4}

2. Membership Testing:
Sets are much more efficient than lists in order to check membership.

3. Set Operations in Algorithms:
Sets are heavily used when solving problems concerning intersections, unions, and differences among data collections.

4. Efficient Lookups:
Since sets use hash tables internally, membership tests are very efficient.