Sets
Introduction / Definition
A set is a collection in which each distinct value occurs at most once. Sets focus on membership and uniqueness rather than position. Common operations include insertion, deletion, union, intersection, and difference. They are useful when duplicate values should automatically be ignored.
Syntax
set = \{1, 2, 3\}
add(set, value)
contains(set, value)
Detailed Explanation
Sets can be understood by identifying its purpose, the rules that govern it, and the way it affects program behavior. The concept should be separated from its particular syntax so that learners can recognize the same idea across different programming languages. A useful way to study it is to start with a small example, trace what happens step by step, and then consider the benefits and limitations. This approach builds both conceptual understanding and practical programming skill.
Example
values = \[1, 2, 2, 3\]
unique = set(values)
print(unique)
Output
\{1, 2, 3\}
Important Points / Notes
- Values are unique.
- Membership is a key operation.
- Order is normally not the main concern.
- Union and intersection are common operations.
- Sets are useful for removing duplicates.
Mini Practice Question
What is the union of {1,2,3} and {3,4,5}?