DEV Community

Vishwa K
Vishwa K

Posted on

Understanding Sets in Python

1Understanding Sets in Python: A Beginner's Guide

Python provides several built-in data structures, and one of the most useful among them is the set. A set is an unordered collection of unique elements. It is commonly used when you need to remove duplicates or perform mathematical set operations.

What is a Set?

A set stores unique values only. If duplicate values are added, Python automatically removes them.

numbers = {1, 2, 3, 3, 4, 4, 5}
print(numbers)

Output:

{1, 2, 3, 4, 5}

As you can see, the duplicate values are removed automatically.

Creating a Set

You can create a set using curly braces "{}".

fruits = {"apple", "banana", "orange"}
print(fruits)

Adding Elements

Use the "add()" method to insert a new element.

fruits.add("mango")
print(fruits)

Removing Elements

Python provides two methods for removing elements:

fruits.remove("banana")

or

fruits.discard("banana")

The difference is that "discard()" does not raise an error if the item is not present.

Checking Membership

Sets provide very fast lookup operations.

if "apple" in fruits:
print("Apple exists")

Set Operations

Union

Combines two sets.

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

print(a | b)

Output:

{1, 2, 3, 4, 5}

Intersection

Returns common elements.

print(a & b)

Output:

{3}

Difference

Returns elements present in the first set but not in the second.

print(a - b)

Output:

{1, 2}

Real-World Example

Removing duplicate email addresses:

emails = [
"user1@gmail.com",
"user2@gmail.com",
"user1@gmail.com"
]

unique_emails = set(emails)
print(unique_emails)

Output:

{'user1@gmail.com', 'user2@gmail.com'}

Advantages of Sets

  • Automatically removes duplicates
  • Fast searching and membership testing
  • Supports mathematical operations like union and intersection
  • Easy to work with large collections of unique data

Conclusion

Sets are one of Python's most powerful data structures for handling unique data efficiently. Whether you're removing duplicates, checking membership, or performing mathematical operations, sets provide a clean and efficient solution.

If you're new to Python, learning sets early will help you write cleaner and faster code.

Top comments (0)