MyInternships.in

Python Data Structures

Python Sets

A set is an unordered collection that automatically removes duplicates, making it the go-to structure whenever you only care about unique values.


Creating a Set

You create a set with curly braces or the set() function. Sets have no fixed order and cannot contain duplicate values — Python silently drops any repeats.

Creating sets
Python
fruits = {"apple", "banana", "apple"}
print(fruits)          # {'apple', 'banana'}

empty = set()          # {} creates a dict, not a set!
nums = set([1, 2, 2, 3])
print(nums)             # {1, 2, 3}

Adding and Removing Items

add() inserts a single item; remove() deletes one, raising an error if it is missing, while discard() removes it silently if present. Because a set is unordered, you cannot access items by index.

add, remove, discard
Python
colors = {"red", "green"}
colors.add("blue")
colors.discard("yellow")  # no error even though it's not there
colors.remove("red")
print(colors)

Set Operations

Sets support fast mathematical operations for comparing two collections — perfect for tasks like finding common tags, shared skills, or unique visitors.

Combining two sets
Python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)  # union: {1, 2, 3, 4, 5, 6}
print(a & b)  # intersection: {3, 4}
print(a - b)  # difference: {1, 2}
print(a ^ b)  # symmetric difference: {1, 2, 5, 6}

Set Operation Reference

OperationOperatorMethodResult
Uniona | ba.union(b)All items from both sets
Intersectiona & ba.intersection(b)Items in both sets
Differencea - ba.difference(b)Items only in a
Symmetric differencea ^ ba.symmetric_difference(b)Items not shared by both
💡

Use a set to quickly remove duplicates from a list: unique_items = list(set(my_list)). Note this loses the original order.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships