Fundamentals 7 min read

Master Python Sets: Unique Collections, Operations, and Practical Tips

This article introduces Python's set collection, covering its definition, unique characteristics, creation methods, common operations such as adding, updating, deleting, immutable frozenset usage, and set mathematics, while comparing it with lists, tuples, and dictionaries to highlight proper data‑structure selection.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Sets: Unique Collections, Operations, and Practical Tips

Preface

Earlier articles introduced Number, String, List, Tuple, and Dict. This article briefly explains the last basic data type in Python: the set collection.

Features

A set is enclosed in curly braces {}. An empty {} creates an empty dictionary, not a set; use set() for an empty set. Elements are unique, unordered, and must be immutable.

Unique elements (no duplicates)

Unordered

Elements must be immutable

Basic Usage

# Define a set
set1 = {1, 2, 3}
print(set1, type(set1))

# Convert a string to a set
set2 = set('hello')
print(set2)

# Duplicate elements are automatically removed
set3 = {1, 2, 3, 1, 2, 3}
print(set3)

# Creating an empty dictionary (incorrect for empty set)
temp1 = {}
print(type(temp1))

# Correct way to create an empty set
temp2 = set()
print(type(temp2))

# Empty list and tuple creation
t1 = ()
t2 = tuple()
print(type(t1), type(t2))

Sets can be iterated but not indexed because they are unordered.

set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
    print(i)

Add Elements

set1 = {1, 2, 3}
set1.add(4)
print(set1)

Update Elements

# Add a single element
set1.update('a')
# Add multiple elements
set1.update(['s', 'ss'])
print(set1)

Delete Elements

set1 = {1, 2, 3, 4, 5, 6, 'aaa', 'sss'}
temp = set1.pop()  # Randomly removes and returns an element
print(set1, temp)

set2 = {1, 2, 3, 4, 5, 6, 'aaa', 'sss'}
set2.remove('aaa')   # Raises KeyError if element not present
set2.discard('sss') # No error if element absent
set2.discard('s')
print(set1)

set2.clear()
print(set2)

Immutable Set (frozenset)

set1 = frozenset('hello')
print(set1)
# set1.add('a')  # Raises AttributeError

Mathematical Operations

set1 = {'aa', 'bb', 'cc', 'zz'}
set2 = {'aa', 'bb', 'dd', 'ee'}

# Intersection
print(set1.intersection(set2))
print(set1 & set2)

# Union
print(set1.union(set2))
print(set1 | set2)

# Difference
print(set1.difference(set2))
print(set1 - set2)

# Symmetric difference
print(set1.symmetric_difference(set2))
print(set1 ^ set2)

# Disjoint test
print(set1.isdisjoint(set2))

# Subset test
print(set1.issubset(set2))

# Superset test
print(set1.issuperset(set2))

Key Takeaway

A good data structure makes programming more efficient.

Summary

In Python, a set is a container for unique, immutable items, useful for deduplication. Lists and tuples store ordered data, with tuples being immutable. Dictionaries store key‑value pairs with unique keys and are optimized for fast lookup. Choosing the right data structure improves code efficiency.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData StructuresSet OperationsTutorialcodingSetfrozenset
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.