|
| 1 | +--- |
| 2 | +id: python-set |
| 3 | +title: Set in Python |
| 4 | +sidebar_label: Set in Python #displays in sidebar |
| 5 | +sidebar_position: 10 |
| 6 | +tags: |
| 7 | + [ |
| 8 | + Python, |
| 9 | + List in Python, |
| 10 | + Introduction of python, |
| 11 | + Python Syntax, |
| 12 | + Variables, |
| 13 | + Operators, |
| 14 | + Type Casting, |
| 15 | + String, |
| 16 | + Tuple in Python, |
| 17 | + Set in Python |
| 18 | + ] |
| 19 | + |
| 20 | +--- |
| 21 | + |
| 22 | +# Set in Python |
| 23 | + |
| 24 | +A **Set** in Python is a built-in data structure used to store multiple **unique** elements in a single variable. Sets are **unordered** and **mutable**, making them an efficient tool for membership tests, eliminating duplicates, and performing mathematical set operations. |
| 25 | + |
| 26 | + |
| 27 | +## Why Use Sets? |
| 28 | + |
| 29 | +Sets are commonly used when: |
| 30 | +- You need to **store unique values only** |
| 31 | +- The order of elements **does not matter** |
| 32 | +- You want to perform **fast membership testing** |
| 33 | +- You need efficient **union, intersection, and difference operations** |
| 34 | + |
| 35 | + |
| 36 | +## Key Characteristics |
| 37 | + |
| 38 | +- **Unordered:** Elements have no defined order. |
| 39 | +- **Unique:** No duplicates allowed. |
| 40 | +- **Mutable:** You can add or remove items. |
| 41 | +- **Iterable:** You can loop through a set. |
| 42 | + |
| 43 | + |
| 44 | +## Creating a Set |
| 45 | + |
| 46 | +There are two main ways to create a set: |
| 47 | + |
| 48 | +### Using Curly Braces `{}` |
| 49 | + |
| 50 | +```python |
| 51 | +fruits = {"apple", "banana", "cherry"} |
| 52 | +print(fruits) # Output: {'banana', 'apple', 'cherry'} |
| 53 | +```` |
| 54 | + |
| 55 | +### Using the `set()` Constructor |
| 56 | + |
| 57 | +```python |
| 58 | +numbers = set([1, 2, 3, 2]) |
| 59 | +print(numbers) # Output: {1, 2, 3} |
| 60 | +``` |
| 61 | + |
| 62 | +> **Important:** Empty curly braces `{}` create an **empty dictionary**, not a set. Use `set()` instead: |
| 63 | +
|
| 64 | +> |
| 65 | +> ```python |
| 66 | +> empty_set = set() |
| 67 | +> ``` |
| 68 | +
|
| 69 | +
|
| 70 | +## Adding Elements to a Set |
| 71 | +
|
| 72 | +You can add elements using the `add()` method: |
| 73 | +
|
| 74 | +```python |
| 75 | +colors = {"red", "green"} |
| 76 | +colors.add("blue") |
| 77 | +print(colors) # Output: {'red', 'green', 'blue'} |
| 78 | +``` |
| 79 | +
|
| 80 | +## Removing Elements from a Set |
| 81 | + |
| 82 | +Python provides several methods to remove elements: |
| 83 | + |
| 84 | +### `remove()` |
| 85 | + |
| 86 | +Removes the specified item. Raises an error if the item does not exist. |
| 87 | + |
| 88 | +```python |
| 89 | +colors = {"red", "green"} |
| 90 | +colors.remove("red") |
| 91 | +print(colors) # Output: {'green'} |
| 92 | +``` |
| 93 | + |
| 94 | +> If you try to remove an item not present: |
| 95 | +> |
| 96 | +> ```python |
| 97 | +> colors.remove("yellow") # KeyError |
| 98 | +> ``` |
| 99 | +
|
| 100 | +
|
| 101 | +### `discard()` |
| 102 | +
|
| 103 | +Removes the specified item without raising an error if the item is not found. |
| 104 | +
|
| 105 | +```python |
| 106 | +colors = {"green"} |
| 107 | +colors.discard("yellow") # No error |
| 108 | +``` |
| 109 | +
|
| 110 | +### `pop()` |
| 111 | + |
| 112 | +Removes and returns an arbitrary element. |
| 113 | + |
| 114 | +```python |
| 115 | +colors = {"red", "blue"} |
| 116 | +removed = colors.pop() |
| 117 | +print("Removed:", removed) |
| 118 | +print("Remaining:", colors) |
| 119 | +``` |
| 120 | + |
| 121 | + |
| 122 | +### `clear()` |
| 123 | + |
| 124 | +Removes all elements. |
| 125 | + |
| 126 | +```python |
| 127 | +colors.clear() |
| 128 | +print(colors) # Output: set() |
| 129 | +``` |
| 130 | + |
| 131 | + |
| 132 | +## Updating a Set |
| 133 | + |
| 134 | +To add multiple items at once, use `update()`: |
| 135 | + |
| 136 | +```python |
| 137 | +a = {1, 2} |
| 138 | +a.update([3, 4], {5, 6}) |
| 139 | +print(a) # Output: {1, 2, 3, 4, 5, 6} |
| 140 | +``` |
| 141 | + |
| 142 | + |
| 143 | +## Membership Testing |
| 144 | + |
| 145 | +Check if an item is in a set using `in` or `not in`: |
| 146 | + |
| 147 | +```python |
| 148 | +nums = {1, 2, 3} |
| 149 | +print(2 in nums) # Output: True |
| 150 | +print(5 not in nums) # Output: True |
| 151 | +``` |
| 152 | + |
| 153 | + |
| 154 | +## Common Set Operations |
| 155 | + |
| 156 | +Python sets support powerful operations: |
| 157 | + |
| 158 | +| Operation | Syntax | Description | | |
| 159 | +| -------------------- | -------------------------------------- | ------------------------------------ | ----------------------------------- | |
| 160 | +| Union | \`a | b`or`a.union(b)\` | Combine all elements from both sets | |
| 161 | +| Intersection | `a & b` or `a.intersection(b)` | Elements common to both sets | | |
| 162 | +| Difference | `a - b` or `a.difference(b)` | Elements in `a` but not in `b` | | |
| 163 | +| Symmetric Difference | `a ^ b` or `a.symmetric_difference(b)` | Elements in either set, but not both | | |
| 164 | + |
| 165 | +--- |
| 166 | + |
| 167 | +### Example |
| 168 | + |
| 169 | +```python |
| 170 | +a = {1, 2, 3} |
| 171 | +b = {3, 4, 5} |
| 172 | + |
| 173 | +# Union |
| 174 | +print(a | b) # {1, 2, 3, 4, 5} |
| 175 | + |
| 176 | +# Intersection |
| 177 | +print(a & b) # {3} |
| 178 | + |
| 179 | +# Difference |
| 180 | +print(a - b) # {1, 2} |
| 181 | + |
| 182 | +# Symmetric Difference |
| 183 | +print(a ^ b) # {1, 2, 4, 5} |
| 184 | +``` |
| 185 | + |
| 186 | +--- |
| 187 | + |
| 188 | +## Iterating Over a Set |
| 189 | + |
| 190 | +Loop through elements with a `for` loop: |
| 191 | + |
| 192 | +```python |
| 193 | +animals = {"cat", "dog", "rabbit"} |
| 194 | +for animal in animals: |
| 195 | + print(animal) |
| 196 | +``` |
| 197 | + |
| 198 | +> Since sets are unordered, the output order may differ every time. |
| 199 | +
|
| 200 | + |
| 201 | +## Frozenset |
| 202 | + |
| 203 | +A **frozenset** is an immutable version of a set. Once created, you cannot modify it. |
| 204 | + |
| 205 | +```python |
| 206 | +fs = frozenset([1, 2, 3]) |
| 207 | +print(fs) # frozenset({1, 2, 3}) |
| 208 | + |
| 209 | +# fs.add(4) # AttributeError |
| 210 | +``` |
| 211 | + |
| 212 | +Use `frozenset` when you need a **hashable set**, e.g., as dictionary keys. |
| 213 | + |
| 214 | + |
| 215 | +## When to Use Sets? |
| 216 | + |
| 217 | +* Removing duplicates from lists |
| 218 | +* Fast membership tests |
| 219 | +* Performing set algebra (union, intersection) |
| 220 | +* Representing unique collections |
| 221 | + |
| 222 | + |
| 223 | +## Best Practices |
| 224 | + |
| 225 | +* Use `set()` to create empty sets. |
| 226 | +* Use `discard()` if you are not sure whether an element exists. |
| 227 | +* Prefer sets over lists when you need uniqueness or fast lookups. |
| 228 | + |
| 229 | +--- |
| 230 | + |
| 231 | +## Practice Exercises |
| 232 | + |
| 233 | +1. **Create a set of your favorite fruits. Add one more fruit and remove another.** |
| 234 | +2. **Find the union and intersection of `{1, 2, 3}` and `{3, 4, 5}`.** |
| 235 | +3. **Write a program that removes duplicates from a list using a set.** |
| 236 | +4. **Create a frozenset and show that it cannot be modified.** |
| 237 | + |
| 238 | +--- |
| 239 | + |
| 240 | +## Summary Table |
| 241 | + |
| 242 | +| Feature | Description | |
| 243 | +| --------------------- | -------------------------------------------- | |
| 244 | +| **Mutable** | Yes (can add/remove elements) | |
| 245 | +| **Ordered** | No | |
| 246 | +| **Duplicates** | Not allowed | |
| 247 | +| **Empty Declaration** | `set()` | |
| 248 | +| **Immutable Variant** | `frozenset` | |
| 249 | +| **Typical Use Cases** | Membership tests, uniqueness, set operations | |
| 250 | + |
0 commit comments