beginnerData Structures

Sets

Unordered collections of unique elements for math operations.

01Creating Sets

Sets store unique elements and support fast membership testing.

Python
1fruits = {"apple", "banana", "cherry", "apple"}
2print(fruits) # duplicates removed
3
4nums = set([1, 2, 2, 3, 3, 3])
5print(nums) # {1, 2, 3}
Output
{'cherry', 'apple', 'banana'}
{1, 2, 3}

02Set Operations

Sets support mathematical operations like union, intersection, difference.

Python
1a = {1, 2, 3, 4}
2b = {3, 4, 5, 6}
3
4print(a | b) # Union: {1, 2, 3, 4, 5, 6}
5print(a & b) # Intersection: {3, 4}
6print(a - b) # Difference: {1, 2}
7print(a ^ b) # Symmetric diff: {1, 2, 5, 6}
Output
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{1, 2, 5, 6}