Intermediate Topic 21 of 54 Programming Fundamentals
Sets
Unordered collections of unique elements supporting union and intersection.
How it works
A set stores unique items, backed by a hash table or a balanced tree, with fast membership tests and set algebra such as union, intersection and difference. Adding an existing item has no effect. Hash-based sets give average O(1) operations but no order, whereas tree-based sets keep elements sorted.
Step-by-step walkthrough
- Set A and set B each hold unique elements.
- Union combines everything: 1 2 3 4 5.
- Union also takes B.
- Intersection keeps only the shared element 3.
- Intersection also checks B.
Where it is used
Removing duplicates, checking permissions, finding common friends between users, tracking visited nodes in graph search and comparing two lists for differences are typical uses. Sets express intent more clearly than lists filtered by hand.
Common pitfall
Sets are unordered, and elements must be hashable, so lists and other mutable items cannot be stored directly. Do not rely on iteration order. Converting a list to a set to deduplicate loses the original order unless you handle it explicitly.
Where it fits in the course
Sets is topic 21 of 54 in Programming Fundamentals, rated Intermediate. It follows Dictionaries and Maps. The next topic is Tuples.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Sets?
Where do people use Sets?
What is the most common mistake with Sets?
What should I learn before this topic?
How can I practice it?
Is Sets hard to learn?
How long does it take to learn Sets?
Which topics are related to Sets?
What should I study after Sets?
Related topics
- Dictionaries and Maps (Programming Fundamentals)
- Tuples (Programming Fundamentals)
- Strings (Programming Fundamentals)
- Recursion (Programming Fundamentals)
- Sets and Set Operations (Theory & Discrete Math)
- Training and Test Sets (AI & Machine Learning)
- Union of Sets with Bitsets (Data Structures)