Back to course

Sets: Unordered Collections of Unique Elements

Python Programming: The 0 to Hero Bootcamp

Sets

A set is an unordered collection of unique, immutable elements. Sets are highly useful for tasks involving membership testing and eliminating duplicate values.

Sets are defined using curly braces {}.

Creating Sets

Note that the order of elements is not guaranteed.

python

Creating a set

my_set = {1, 2, 3, 3, 4, 1} print(my_set) # Output: {1, 2, 3, 4} (Duplicates removed)

Creating an empty set (Important: {} creates an empty dictionary, not a set!)

empty_set = set()

Adding and Removing Elements

Sets are mutable (you can add/remove items), but the items themselves must be immutable (you cannot put a list inside a set).

python letters = {'a', 'b', 'c'} letters.add('d') print(letters) # {'c', 'b', 'a', 'd'} (order varies)

letters.remove('a') # Removes 'a'. Raises KeyError if item not found.

letters.discard('z') # Removes 'z' if present, but does NOT raise an error. print(letters)

Membership Testing (Fast)

Checking if an item is in a set is extremely fast, making sets ideal for large membership checks.

python if 'b' in letters: print("b is here.")