Sobes.tech
Junior — Middle

What is the purpose and features of the set data structure in Python?

sobes.tech AI

Answer from AI

In Python, a set is an unordered collection of unique elements. Its main purpose is to store a collection of values without duplicates and to provide fast search, addition, and removal of elements.

Features of set:

  • Elements must be hashable (e.g., numbers, strings, tuples).
  • No indices, elements are unordered.
  • Supports set operations: union, intersection, difference, symmetric difference.

Example usage:

s = set([1, 2, 3, 2])  # duplicates will be removed
s.add(4)
s.remove(1)
print(s)  # Will output {2, 3, 4}

# Set operations
s1 = {1, 2, 3}
s2 = {3, 4, 5}
print(s1 & s2)  # intersection {3}
print(s1 | s2)  # union {1, 2, 3, 4, 5}