Python Sets

Introduction Reading Time: 10 min

Table of Contents

Description

A set in Python is an unordered, unindexed, and mutable collection of unique elements. It is defined using curly braces {} or the set() constructor.
Key characteristics:
Automatically removes duplicates.
Does not allow indexing or slicing.
Supports mathematical set operations like union, intersection, and difference.

Prerequisites

  • Basic knowledge of Python data types like lists and tuples.
  • Understanding of loops and conditions is helpful.

Examples

Here's a simple program in Python:

# Creating a set
fruits = {"apple", "banana", "cherry"}

# Automatically removes duplicates
numbers = {1, 2, 2, 3}
print(numbers)  # Output: {1, 2, 3}

# Adding elements to a set
fruits.add("orange")  # Adds 'orange' to the set

# Removing elements
fruits.remove("banana")  # Removes 'banana'
# fruits.remove("grape")  # Error if not found
fruits.discard("grape")   # No error if not found

# Checking membership
print("apple" in fruits)  # True

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}

print(a.union(b))         # {1, 2, 3, 4, 5}
print(a.intersection(b))  # {3}
print(a.difference(b))    # {1, 2}
print(a.symmetric_difference(b))  # {1, 2, 4, 5}

# Clearing a set
a.clear()
print(a)  # Output: set()
      

Real-World Applications

Removing duplicate data from user inputs or datasets.

Tag systems in blogs or recommendation engines.

Efficient membership testing (in operation is fast).

Mathematical simulations and operations.

Data comparison and filtering.

Where topic Can Be Applied

Data preprocessing: Removing duplicate records.

Natural Language Processing (NLP): Identifying unique words.

Web development: User role/tag systems.

Cybersecurity: Tracking unique IPs or access logs.

Machine learning: Unique feature/value tracking.

Resources

Topic video source

A comprehensive video

Watch

Python pdf

pdf on topic

Visit

Interview Questions

What is a set in Python?

How is a set different from a list or tuple?

Can a set contain other sets?

What happens if you add a duplicate to a set?

Explain union(), intersection(), and difference() methods.