Sets and Related Operations

A set is an unordered collection of unique items. Sets automatically remove duplicates, which makes them useful whenever you need to work with distinct values only.

Creating a Set

fruits = {"apple", "banana", "mango"}
numbers = set([1, 2, 2, 3, 3, 3])
print(numbers)

Adding and Removing Items

fruits.add("orange")
fruits.remove("banana")
print(fruits)

Set Operations

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
Sets are commonly used to quickly find unique values in a dataset or to check overlap between two groups of records, without writing manual loops to remove duplicates.

Coming Up

The next topic introduces dictionaries, which store data as key-value pairs and are one of the most flexible data structures in Python.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course