← Back to Python

All Topics

Advertisement

Learn/Python/Python Fundamentals

Sets

Topic: Data Structures

Advertisement

Introduction

Sets are unordered collections of unique elements. They are useful for membership testing and eliminating duplicates.

Creating Sets

# Basic set
fruits = {"apple", "banana", "cherry"}

# From list (removes duplicates)
nums = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

# Empty set (not {})
empty = set()

Set Operations

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

# Union
print(a | b)      # {1, 2, 3, 4, 5, 6}
print(a.union(b))

# Intersection
print(a & b)      # {3, 4}
print(a.intersection(b))

# Difference
print(a - b)      # {1, 2}
print(a.difference(b))

# Symmetric difference
print(a ^ b)      # {1, 2, 5, 6}

Set Methods

s = {1, 2, 3}

s.add(4)          # Add element
s.remove(2)      # Remove (raises error if not found)
s.discard(5)      # Remove (no error)
s.pop()           # Remove and return arbitrary element
s.clear()         # Empty the set

Practice Problems

  1. Find common elements in two lists
  2. Remove all duplicates from a list
  3. Check if one set is subset of another
  4. Find elements in first list but not in second
  5. Implement set operations for given data

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →