Labs ICT
Pro Login

Sets

Python Sets

A set is an unordered collection of unique elements written with curly braces {}. Duplicates are automatically removed. Sets are mutable but can only contain immutable items.

Creating Sets

Use curly braces or the set() constructor.

fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)
empty_set = set()
Try it Yourself →

Set Operations

Union, intersection, difference, and symmetric difference.

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)
print(a & b)
print(a - b)
print(a ^ b)
Try it Yourself →

Set Methods

Useful methods: add(), remove(), discard(), pop(), clear().

nums = {10, 20, 30}
nums.add(40)
nums.discard(20)
removed = nums.pop()
print(nums)
print(f"Removed: {removed}")
Try it Yourself →