Sobes.tech
Junior

What is a set in the context of Python and how to use it?

sobes.tech AI

Answer from AI

Set - an unordered, mutable collection of unique elements. Elements of a set must be of an immutable (hashable) type.

Main properties:

  • Unordered: Elements have no indices, and the order of addition is not preserved.
  • Uniqueness: Each element appears only once in the set. Duplicates are automatically removed.
  • Mutability (for set): Elements can be added and removed. There is also an immutable version — frozenset.
  • Hashability of elements: Elements must be immutable (numbers, strings, tuples). Lists, dictionaries, and other sets cannot be elements of a set.

Creating a set:

Using curly braces {} or the set() function. An empty set is created only with set(), as {} creates an empty dictionary.

// Creating a set from elements
my_set = {1, 2, 3, 4, 1} # Duplicate 1 will be ignored
// my_set contains {1, 2, 3, 4}

// Creating a set from an iterable
another_set = set([3, 4, 5, 5])
// another_set contains {3, 4, 5}

// Creating an empty set
empty_set = set()

Main operations:

Operation Syntax / Method Description Example
Add element add() Adds one element. If the element exists, nothing happens. my_set.add(5)
Remove element remove() Removes the specified element. Raises an error if the element does not exist. my_set.remove(2)
Discard element discard() Removes the specified element. Does not raise an error if the element does not exist. my_set.discard(2)
Pop element pop() Removes and returns an arbitrary element. Raises an error if the set is empty. element = my_set.pop()
Clear set clear() Removes all elements from the set. my_set.clear()
Union | or union() Returns a new set containing all unique elements from both sets. set1 | set2 or set1.union(set2)
Intersection & or intersection() Returns a new set with common elements. set1 & set2 or set1.intersection(set2)
Difference - or difference() Returns a new set with elements from the first set that are not in the second. set1 - set2 or set1.difference(set2)
Symmetric difference ^ or symmetric_difference() Returns a new set with elements in either set but not in both. set1 ^ set2 or set1.symmetric_difference(set2)
Check presence in Returns True if the element is in the set, otherwise False. 3 in my_set

Using frozenset:

frozenset is an immutable version of a set. It can be used where a hashable set object is required (e.g., as a dictionary key or as an element of another set).

// Creating a frozenset
immutable_set = frozenset([1, 2, 3])

// f = {immutable_set: "key"} // frozenset can be a dictionary key
// mutable_set.add(immutable_set) // frozenset can be an element of a set

Applications:

  • Fast checking for element uniqueness in a collection.
  • Performing set operations (union, intersection, etc.).
  • Removing duplicates from a list or other iterable collection.