Labs ICT
Pro Login

Sets

1 min read | Python Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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()

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)

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}")