Sets

A set is a collection data type in Python used to store multiple items in a single variable.
Sets are unordered, unchangeable (no index-based modification), and do not allow duplicate values.

Sets are mainly used when you need unique values.

CREATING A SET

Sets are created using curly brackets { }.

numbers = {1, 2, 3, 4, 5}

Sets automatically remove duplicate values:

values = {1, 2, 2, 3, 4, 4}
print(values)

Output will contain only unique numbers.

IMPORTANT CHARACTERISTICS

β€’ Unordered (no indexing)
β€’ No duplicate values
β€’ Mutable (you can add or remove items)
β€’ Items must be immutable (numbers, strings, tuples)

ACCESSING SET ITEMS

Sets do not support indexing because they are unordered.
You can access items using a loop.

fruits = {"Apple", "Banana", "Mango"}for fruit in fruits:
print(fruit)

ADDING ITEMS TO A SET

add() – Adds a single item

numbers = {1, 2, 3}
numbers.add(4)

update() – Adds multiple items

numbers.update([5, 6, 7])

REMOVING ITEMS FROM A SET

remove() – Removes specific item (error if not found)

numbers.remove(3)

discard() – Removes item (no error if not found)

numbers.discard(10)

pop() – Removes a random item

numbers.pop()

clear() – Removes all items

numbers.clear()

SET OPERATIONS

Sets support mathematical operations.

Union ( | )

a = {1, 2, 3}
b = {3, 4, 5}print(a | b)

Intersection ( & )

print(a & b)

Difference ( – )

print(a - b)

Symmetric Difference ( ^ )

print(a ^ b)

SET METHODS

a = {1, 2, 3}
b = {3, 4, 5}print(a.union(b))
print(a.intersection(b))
print(a.difference(b))

WHEN TO USE SETS

β€’ When you need unique values
β€’ For removing duplicates from a list
β€’ For mathematical set operations
β€’ For membership testing (faster than lists)

Example removing duplicates:

numbers = [1, 2, 2, 3, 4, 4]
unique_numbers = set(numbers)
print(unique_numbers)

IMPORTANT POINTS

β€’ Sets are unordered
β€’ No indexing allowed
β€’ Do not allow duplicate values
β€’ Mutable, but elements must be immutable

Understanding sets helps you work efficiently with unique and mathematical data operations in Python.

Home Β» PYTHON INTERMEDIATE (PYI) > Data Structures > Sets