Computer ScienceChapter 3: Programming Fundamentals
3.2.3 Sets
Set
Explanation level
Introduction
Sets in Python are collections of unique and unordered elements. A set cannot contain duplicate values — if the same value is added more than once, the set will only hold one instance of it. Sets are represented using curly braces `{}`.
The textbook explains that sets can be used to store a list of unique usernames, product IDs, and similar data where duplication is not allowed. Using the `in` operator, it is easy to check whether a particular element exists in a set.
Definition
Set is a collection of unique and unordered elements in Python, represented using curly braces `{}`, where duplicate values are automatically removed.
In simple words: A set is a collection that automatically removes duplicates and does not keep items in any specific order.
Main Idea
- Unique elements: No duplicates are allowed. If you try to add a duplicate, it is simply ignored.
- Unordered: The elements do not have a fixed position (no index). You cannot access elements by index like you do with lists or tuples.
- Store unique values.
- Quickly check if an element exists.
- Remove duplicates from a collection.
Core Concept
Creating a Set A set is created by placing elements inside curly braces `{}`, separated by commas.
Example from the book (line 1): ```python grades = 85, 92, 78, 92, 85, 95 ``` This creates a set named `grades`. Notice that duplicate grades (85 and 92) exist in the initial assigned values. Since sets only store unique values, the duplicates are automatically removed.
Output from the book (line 2): ```python print(grades) ``` Output: `{92, 85, 78, 95}`
- The duplicates (85 and 92) appear only once.
- The order is not the same as the input order (sets are unordered).
Adding an Element The `add()` method adds a new element to the set.
Example from the book (line 3): ```python grades.add(88) ``` This adds `88` to the set.
Output from the book (line 4): ```python print(grades) ``` Output: `{78, 85, 88, 92, 95}`
Checking if a Value Exists The `in` operator is used to check if a specific value exists in the set.
Example from the book (lines 5–6): ```python if 92 in grades: print("Student has 92 among the grades.") ``` Output from the book: `Student has 92 among the grades.`
Key Characteristics of Sets
| Feature | Description |
|---|---|
| Unique | No duplicate values allowed. Duplicates are automatically removed. |
| Unordered | Elements do not have a fixed position. No indexing. |
| Mutable | You can add or remove elements after creation. |
| No indexing | You cannot access elements by index (e.g., `grades[0]` is not valid). |
| Fast membership testing | The `in` operator is very fast for sets. |
Intermediate Level
Sets are different from lists and tuples in important ways:
| Feature | List | Tuple | Set |
|---|---|---|---|
| Duplicates | Allowed | Allowed | Not allowed |
| Order | Ordered | Ordered | Unordered |
| Indexing | Yes | Yes | No |
| Mutability | Mutable | Immutable | Mutable |
| Syntax | `[]` | `()` | `{}` |
The textbook shows that when a set is created with duplicates, the duplicates are automatically removed. This is useful when you need to ensure that a collection contains only unique values.
The `in` operator is particularly efficient for sets. Checking if a value exists in a set is faster than checking in a list, especially for large collections.
Important Points
- - Set: A collection of unique and unordered elements in Python.
- - Created using curly braces `{}`.
- - Duplicates are automatically removed.
- - Unordered: No indexing, no fixed position.
- - Mutable: Can add or remove elements.
- - `add()` method: Adds an element to the set.
- - `in` operator: Checks if a value exists in the set.
- - Use cases: Unique usernames, product IDs, removing duplicates.
Remember
- - **Set** = Unique + Unordered.
- - Created with `{}`.
- - No duplicates — automatically removed.
- - No indexing — cannot use `grades[0]`.
- - **0** = Add element.
- - **0** = Check existence.
- - Use for unique values (usernames, product IDs).
Common Mistakes
- 1. Trying to access a set by index — Sets are unordered and do not support indexing.
- 2. Expecting a specific order when printing a set — The order of elements in a set is not guaranteed.
- 3. Thinking `add()` works like `append()` — `add()` adds a single element; there is no `append()` for sets.
- 4. Confusing sets with dictionaries — Both use `{}`, but dictionaries store key-value pairs, while sets store single values.
- 5. Trying to add a duplicate — Duplicates are silently ignored; no error is raised.
- 6. Using a set when order matters — If you need ordered data, use a list or tuple instead.
Quick Revision
- Set: A collection of unique and unordered elements in Python, represented using curly braces `{}`.
- Key features:
- Unique elements (duplicates automatically removed).
- Unordered (no indexing).
- Mutable (can add or remove elements).
- Operations:
- `add(value)`: Adds an element to the set.
- `in` operator: Checks if a value exists in the set.
- Example:
- Use cases: Unique usernames, product IDs, removing duplicates.
60-Second Revision
- **Set** = Unique + Unordered.
- Created with `{}`.
- No duplicates — automatically removed.
- No indexing — cannot use `grades[0]`.
- **0** = Add element.
- **0** = Check existence.
- Use for unique values (usernames, product IDs).
- Warning: Order is not guaranteed in a set.
Frequently Asked Questions (FAQs)
Q1. What is a set in Python? Answer: A set is a collection of unique and unordered elements in Python, represented using curly braces `{}`. Sets cannot contain duplicate values, and the order of elements is not guaranteed.
- Q2. How do you create a set?
- Answer: A set is created by placing elements inside curly braces `{}`, separated by commas. For example, `grades = 85, 92, 78, 92, 85, 95`.
- Q3. What happens if you add duplicate values to a set?
- Answer: Duplicates are automatically removed. A set only holds one instance of each value, even if the same value is added multiple times.
- Q4. Can you access elements in a set by index?
- Answer: No, sets are unordered and do not support indexing. You cannot use `grades[0]` to access an element.
- Q5. How do you add an element to a set?
- Answer: Use the `add()` method. For example, `grades.add(88)` adds `88` to the set.
- Q6. How do you check if a value exists in a set?
- Answer: Use the `in` operator. For example, `if 92 in grades:` checks if `92` is in the set.
Q7. What are sets used for? Answer: Sets are used for storing unique values, such as usernames, product IDs, or any collection where duplicates are not allowed. They are also useful for removing duplicates from a list or checking membership efficiently.
- Q8. How is a set different from a list?
- Answer: A list is ordered and allows duplicates, while a set is unordered and does not allow duplicates. Lists support indexing, while sets do not.
- Q9. How is a set different from a tuple?
- Answer: A tuple is ordered and immutable (cannot be changed), while a set is unordered and mutable (can be changed). Tuples allow duplicates, while sets do not.
Q10. Why is the order of elements in a set not guaranteed? Answer: Sets are implemented using hash tables, which do not preserve insertion order. The order of elements in a set depends on the hash values of the elements, which can vary. Therefore, the order is not guaranteed.
Practice Questions
Short Response Questions (SRQs)
- Define a set in Python and explain its key features.
- How do you create a set? Give an example.
- What happens when you add duplicate values to a set?
- How do you check if a value exists in a set?
- What are the differences between a set and a list?
Extended Response Questions (ERQs)
- Discuss the characteristics of sets in Python. Why are they considered unique and unordered?
- Compare and contrast sets, lists, and tuples in Python. In what situations would you choose one over the others?
- Explain the operations that can be performed on sets (`add()`, `in` operator) with examples.
- Analyze the importance of sets in Python programming. Provide real-world examples of when sets are the appropriate data structure.
- You are writing a Python program to store unique usernames. Explain why you would use a set instead of a list, and demonstrate how to create, add to, and check membership in the set.
Multiple Choice Questions (MCQs)
- Q1. What is a set in Python?
- A. An ordered collection of items
- B. A collection of unique and unordered elements
- C. A type of dictionary
- D. A type of function
- Correct Answer: B
- Explanation: A set is a collection of unique and unordered elements.
- Q2. How is a set created?
- A. Using square brackets `[]`
- B. Using curly braces `{}`
- C. Using parentheses `()`
- D. Using angle brackets `<>`
- Correct Answer: B
- Explanation: Sets are created using curly braces `{}`.
- Q3. What happens if you add a duplicate value to a set?
- A. It is added twice
- B. It raises an error
- C. It is automatically removed
- D. It replaces the existing value
- Correct Answer: C
- Explanation: Duplicates are automatically removed in a set.
- Q4. Can you access elements in a set by index?
- A. Yes, using `grades[0]`
- B. Yes, using `grades.get(0)`
- C. No, sets are unordered and do not support indexing
- D. Yes, using `grades.first()`
- Correct Answer: C
- Explanation: Sets are unordered and do not support indexing.
- Q5. How do you add an element to a set?
- A. Using `append()`
- B. Using `insert()`
- C. Using `add()`
- D. Using `push()`
- Correct Answer: C
- Explanation: The `add()` method is used to add an element to a set.
- Q6. How do you check if a value exists in a set?
- A. Using the `in` operator
- B. Using the `exists()` function
- C. Using the `find()` function
- D. Using the `check()` function
- Correct Answer: A
- Explanation: The `in` operator checks if a value exists in a set.
- Q7. What is the output of the following code?
- ```python
- grades = 85, 92, 78, 92, 85, 95
- print(grades)
- ```
- A. `{85, 92, 78, 92, 85, 95}`
- B. `{92, 85, 78, 95}`
- C. `[85, 92, 78, 92, 85, 95]`
- D. `{85, 78, 95}`
- Correct Answer: B
- Explanation: Duplicates are automatically removed, and the set contains only unique values.
- Q8. Which of the following is true about sets?
- A. They are ordered
- B. They allow duplicates
- C. They are unordered
- D. They support indexing
- Correct Answer: C
- Explanation: Sets are unordered, meaning the elements do not have a fixed position.
- Q9. When should you use a set instead of a list?
- A. When you need to maintain order
- B. When you need to store unique values
- C. When you need to access elements by index
- D. When you need to store duplicates
- Correct Answer: B
- Explanation: Sets are used when you need to store unique values and avoid duplicates.
- Q10. What is the output of the following code?
- ```python
- grades = 85, 92, 78, 92, 85, 95
- grades.add(88)
- print(grades)
- ```
- A. `{85, 92, 78, 92, 85, 95, 88}`
- B. `{78, 85, 88, 92, 95}`
- C. `[78, 85, 88, 92, 95]`
- D. `{88, 92, 85, 78, 95}`
- Correct Answer: B
- Explanation: The set contains unique values, and `88` is added. The order may vary, but the values are `{78, 85, 88, 92, 95}`.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.2.3 Sets
Sticky Notes · Quick Revision
Key Point 1
- **Set** = Unique + Unordered.
Key Point 2
- Created with `{}`.
Key Point 3
- No duplicates — automatically removed.
Key Point 4
- No indexing — cannot use `grades[0]`.
Key Point 5
- **0** = Add element.
Key Point 6
- **0** = Check existence.
Key Point 7
- Use for unique values (usernames, product IDs).
Key Point 8
- Order is not guaranteed.
Same supplied content as this Notes page (shared canonical source).