set Data TypeA complete beginner-friendly guide explaining Python sets, their methods, behavior, and real-world use cases.
A set in Python is an unordered collection of unique elements. This means:
# Creating a set
```
numbers = {1, 2, 3, 4}
print(numbers) in keyword)# Removing duplicates using set
```
nums = [1, 2, 2, 3, 3, 4]
unique_nums = set(nums)
print(unique_nums) # Empty set (important!)
```
empty_set = set()
# Set with values
fruits = {"apple", "banana", "mango"}
```
⚠️ {} creates a dictionary, not a set.
Adds an element to the set
colors = {"red", "blue"}
```
colors.add("green") Removes an element (error if not found)
colors.remove("red")
Removes element (no error if missing)
colors.discard("yellow")
Removes a random element
item = colors.pop()
Removes all elements
colors.clear()
a = {1, 2, 3}
```
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(a ^ b) # Symmetric Difference