The set()
function creates a collection of unique, unordered items. It’s useful for removing duplicates, performing set operations (union, intersection), and improving membership tests.
Example
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
Output:
{1, 2, 3, 4, 5}
Duplicates are removed automatically.
Syntax
set(iterable)
- iterable (optional) → A sequence (
list
,tuple
,string
) to convert into a set. - Returns → A set of unique elements.
1. Creating a Set from a List
fruits = ["apple", "banana", "apple", "cherry"]
fruit_set = set(fruits)
print(fruit_set)
# Output: {'banana', 'cherry', 'apple'}
Sets remove duplicates automatically.
2. Creating an Empty Set
empty_set = set() # Correct way
print(type(empty_set)) # Output: <class 'set'>
Do not use {}
→ This creates an empty dictionary, not a set.
3. Checking Membership in a Set (in
)
numbers = {1, 2, 3, 4}
print(2 in numbers) # Output: True
print(5 in numbers) # Output: False
Faster than checking in a list or tuple.
4. Adding and Removing Items in a Set
s = {1, 2, 3}
s.add(4) # Adds 4
s.remove(2) # Removes 2
print(s) # Output: {1, 3, 4}
add(x)
→ Addsx
to the set.remove(x)
→ Removesx
(raises error if missing).discard(x)
→ Removesx
(no error if missing).
5. Set Operations (Union, Intersection, Difference)
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # Union → {1, 2, 3, 4}
print(a & b) # Intersection → {2, 3}
print(a - b) # Difference → {1}
|
(Union) → Combines elements.&
(Intersection) → Finds common elements.-
(Difference) → Elements ina
but notb
.
Key Notes
- ✔ Stores unique, unordered elements.
- ✔ Removes duplicates automatically.
- ✔ Supports fast membership checks (
in
). - ✔ Supports set operations (union, intersection, difference).
By using set()
, you can handle unique values efficiently, compare collections, and perform fast lookups. 🚀