⬅ Previous Topic
ArraysNext Topic ⮕
Dictionaries⬅ Previous Topic
ArraysNext Topic ⮕
DictionariesA Set is an unordered collection of unique elements. Unlike lists or arrays, sets do not allow duplicate values. They are useful in situations where you need to maintain a group of items without repetition and perform operations like union, intersection, and difference.
Let’s start by creating a simple set with a few elements.
SET fruits = {"apple", "banana", "cherry", "apple"}
PRINT fruits
{"apple", "banana", "cherry"}
Notice how the set automatically removed the duplicate "apple". This is one of the core features of sets — uniqueness.
You can add or remove items from a set using standard operations.
SET numbers = {1, 2, 3}
ADD 4 TO numbers
REMOVE 2 FROM numbers
PRINT numbers
{1, 3, 4}
What happens if you try to remove an element that doesn't exist in the set?
In many languages or pseudocode standards, this results in either no change or an error depending on how the "remove" operation is defined. It's common to check for the item before attempting removal.
Let’s explore some common set operations: union, intersection, and difference.
SET A = {1, 2, 3}
SET B = {3, 4, 5}
SET unionAB = A UNION B
SET intersectAB = A INTERSECT B
SET diffAB = A DIFFERENCE B
PRINT unionAB
PRINT intersectAB
PRINT diffAB
{1, 2, 3, 4, 5} {3} {1, 2}
You can quickly test whether an item exists in a set.
SET vowels = {"a", "e", "i", "o", "u"}
IF "e" IN vowels THEN
PRINT "Yes"
ELSE
PRINT "No"
END IF
Yes
Why are sets considered more efficient for membership testing than lists?
Because sets use hashing or similar structures internally to optimize lookup operations, making them typically faster (often constant time) compared to linear search in lists.
Sets are a foundational data structure in programming, offering elegant solutions for problems involving uniqueness, membership, and mathematical group operations. Once understood, they become an indispensable tool in your problem-solving toolkit.
⬅ Previous Topic
ArraysNext Topic ⮕
DictionariesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.