Sobes.tech
Junior — Middle

What are the features of the built-in set data type in Python?

sobes.tech AI

Answer from AI

The built-in set type in Python represents an unordered collection of unique elements.

Main features:

  • Set elements are unique — duplicates are automatically removed.
  • Sets are mutable, but the elements inside must be hashable (immutable).
  • They support efficient set operations: union (|), intersection (&), difference (-), symmetric difference (^).

Example:

s = set([1, 2, 3, 2])  # duplicate 2 will be removed
print(s)  # {1, 2, 3}

s.add(4)  # add an element
s.remove(1)  # remove an element

# set operations
s2 = {3, 4, 5}
print(s & s2)  # intersection {3, 4}
print(s | s2)  # union {2, 3, 4, 5}

Sets are useful for quickly removing duplicates and performing mathematical operations on collections.