Sets in Python are used to store multiple unique values in a single variable. Unlike lists and tuples, sets are unordered, unindexed, and do not allow duplicate elements.
Sets are written using curly braces {}.
Why Sets Are Important
Sets are useful when:
- You want to store unique values
- Remove duplicates from data
- Perform mathematical set operations
- Check membership efficiently
Example:
numbers = {1, 2, 3, 4}
Creating a Set in Python
fruits = {"apple", "banana", "mango"}
mixed = {1, "Python", True}
Duplicate Values in Sets
Sets automatically remove duplicates.
nums = {1, 2, 2, 3}
print(nums)
Output:
{1, 2, 3}
Accessing Set Items
Since sets are unordered, you cannot access items using indexes. You can iterate using loops.
for fruit in fruits:
print(fruit)
Adding Items to a Set
fruits.add("orange")
fruits.update(["kiwi", "grapes"])
Removing Items from a Set
fruits.remove("apple")
fruits.discard("banana")
fruits.pop()
Set Operations
Python supports mathematical set operations.
Union
a = {1, 2}
b = {3, 4}
print(a | b)
Intersection
print(a & b)
Difference
print(a - b)
Symmetric Difference
print(a ^ b)
Common Set Methods
| Method | Description |
|---|---|
| add() | Adds item |
| remove() | Removes item |
| union() | Combines sets |
| intersection() | Common items |
Conclusion
Sets are powerful for handling unique data and performing fast operations. They are commonly used in data cleaning, comparisons, and membership checks.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/