Python Set
1. Creating a Set
empty_set = set()
unique_numbers = {1, 2, 3, 4}
mixed_set = {1, "Python", 3.5, True}
print(empty_set)
print(unique_numbers)
print(mixed_set)Sets are unordered collections of unique elements.
2. Automatic Removal of Duplicates
numbers = {1, 2, 2, 3, 3, 4}
print(numbers) # Output: {1, 2, 3, 4}Duplicate values are automatically discarded.
3. Adding Elements to a Set
fruits = {"apple", "banana"}
fruits.add("orange")
print(fruits)Use add() to insert a single new element.
4. Adding Multiple Elements with update()
update() allows batch insertion from iterables.
5. Removing Elements from a Set
remove()raises an error if missingdiscard()fails silently
6. Set Length and Membership
Efficient for membership testing.
7. Iterating Through a Set
Iteration order is not guaranteed.
8. Mathematical Set Operations
Supports standard mathematical set logic.
9. Subset and Superset Checks
Used for hierarchical relationship validation.
10. Converting Sets to Other Types
Conversion enables ordered or indexed operations when needed.
Last updated