</>
Skip to content
DSA lessons (17/55)

DSA — Sets

What is a Set?

An unordered collection of unique elements.

# Creating sets
s = {1, 2, 3, 4, 5}
s = set([1, 2, 3, 4, 5])
s = set()  # Empty set

Set Operations

# Add
s.add(6)

# Remove
s.remove(3)
s.discard(10)  # No error if not found

# Membership
3 in s

# Size
len(s)

Set Mathematics

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

# Union
a | b  # {1, 2, 3, 4, 5, 6}

# Intersection
a & b  # {3, 4}

# Difference
a - b  # {1, 2}

# Symmetric Difference
a ^ b  # {1, 2, 5, 6}

Use Cases

# Remove duplicates
lst = [1, 2, 2, 3, 3, 3]
unique = list(set(lst))

# Fast membership testing
valid_ids = {101, 102, 103, 104}
if user_id in valid_ids:
    print("Valid")

Mini Practice

  1. Create and manipulate sets
  2. Perform set operations
  3. Remove duplicates from a list
  4. Find common elements

Up Next

Continue with Trees — tree data structure.

Related Topics

Frequently Asked Questions about Sets

What is Sets in DSA?

Sets is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Sets?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sets.

Why is Sets important in DSA?

Sets is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.