🎯

How to Use Sets in Python

PythonBeginner

Work with unordered collections of unique items.

Code Example

Python
# Sets in Python
fruits = {"apple", "banana", "cherry", "apple"}
print(f"Set: {fruits}")  # Duplicates removed

# Add items
fruits.add("date")
print(f"After add: {fruits}")

# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

print(f"\nUnion: {set1 | set2}")
print(f"Intersection: {set1 & set2}")
print(f"Difference: {set1 - set2}")
print(f"Symmetric diff: {set1 ^ set2}")

# Check membership
print(f"\n3 in set1: {3 in set1}")

Explanation

Sets are unordered collections of unique items. Support union (|), intersection (&), difference (-), and symmetric difference (^).

Related Tutorials