Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Set: Introduction

Python Set - Complete Guide

Learn what sets are in Python, how to create them, and their key characteristics.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to Sets
  • Creating Sets
  • Key Characteristics
  • Set vs List
  • Practical Use Cases
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • What is a set — definition and characteristics
  • Creating sets — syntax and different ways
  • Uniqueness — sets store only unique elements
  • Set vs List — key differences and when to use each
  • Use cases — practical applications of sets

Introduction to Sets

A set is an unordered, mutable collection of unique elements in Python. Sets are defined using curly braces {} and can contain elements of any immutable data type.

The key characteristics of sets are:

  • Unordered — elements have no defined order
  • Unique — duplicate elements are automatically removed
  • Mutable — elements can be added or removed
  • Unindexed — elements cannot be accessed by index
  • Hashable elements — only immutable types can be stored

💡 Key concept: Sets are ideal for storing unique values and performing mathematical set operations like union, intersection, and difference.

Creating Sets

1

Set Creation Methods

Sets can be created using curly braces {} or the set() constructor.

# Using curly braces (most common)
fruits = {"apple", "banana", "cherry"}
print(fruits)  # {'apple', 'banana', 'cherry'}

# Using the set() constructor
numbers = set([1, 2, 3, 4, 5])
print(numbers)  # {1, 2, 3, 4, 5}

# Empty set (must use set() - {} creates an empty dictionary)
empty_set = set()
empty_dict = {}
print(type(empty_set))  # <class 'set'>
print(type(empty_dict)) # <class 'dict'>

# From a string (creates a set of characters)
chars = set("hello")
print(chars)  # {'e', 'h', 'l', 'o'}

# From a range
numbers = set(range(5))
print(numbers)  # {0, 1, 2, 3, 4}

# Mixed data types
mixed = {1, "hello", 3.14, True}
print(mixed)  # {1, 3.14, 'hello'}

Important notes:

  • Use {} for non-empty sets with values
  • Use set() for empty sets
  • Sets automatically remove duplicates
  • Elements must be immutable (hashable)

Quick Check: What is the correct way to create an empty set? (Answer: set() — {} creates an empty dictionary)

Key Characteristics

2

Understanding Set Properties

Sets have several unique properties that distinguish them from other data structures.

# 1. Uniqueness (no duplicates)
numbers = {1, 2, 2, 3, 3, 3, 4}
print(numbers)  # {1, 2, 3, 4} — duplicates removed

# 2. Unordered (order is not guaranteed)
fruits = {"apple", "banana", "cherry"}
print(fruits)  # Order may vary: {'cherry', 'apple', 'banana'}

# 3. Mutable (can be modified)
fruits = {"apple", "banana", "cherry"}
fruits.add("mango")
print(fruits)  # {'apple', 'banana', 'cherry', 'mango'}

fruits.remove("banana")
print(fruits)  # {'apple', 'cherry', 'mango'}

# 4. Unindexed (cannot access by index)
fruits = {"apple", "banana", "cherry"}
# print(fruits[0])  # TypeError: 'set' object is not subscriptable

# 5. Elements must be hashable (immutable)
valid_set = {1, "hello", (1, 2)}  # Valid
# invalid_set = {1, [1, 2]}  # TypeError: unhashable type: 'list'

Key properties:

  • Uniqueness — automatically removes duplicates
  • Unordered — cannot rely on element order
  • Mutable — can add and remove elements
  • Hashable elements — only immutable types allowed
  • No indexing — cannot access by position

Quick Check: Can a set contain a list as an element? (Answer: No — lists are mutable and unhashable)

Set vs List

3

Key Differences

Understanding the differences between sets and lists helps you choose the right data structure for your needs.

# Comparison of set and list

# 1. Uniqueness
my_list = [1, 2, 2, 3, 3, 3, 4]
my_set = {1, 2, 2, 3, 3, 3, 4}
print(my_list)  # [1, 2, 2, 3, 3, 3, 4] — duplicates allowed
print(my_set)   # {1, 2, 3, 4} — duplicates removed

# 2. Ordering
my_list = [1, 2, 3]
my_set = {1, 2, 3}
print(my_list[0])  # 1 — index access works
# print(my_set[0])  # TypeError — no index access

# 3. Performance (membership testing)
import time
large_list = list(range(1000000))
large_set = set(range(1000000))

start = time.time()
999999 in large_list
print(f"List membership: {time.time() - start:.6f}s")

start = time.time()
999999 in large_set
print(f"Set membership: {time.time() - start:.6f}s")

# 4. Mutability
my_list = [1, 2, 3]
my_set = {1, 2, 3}
my_list[0] = 10  # Works
# my_set[0] = 10  # TypeError

When to use each:

  • Use sets when:
    • You need to store unique values
    • Fast membership testing is important
    • Order doesn't matter
    • You need mathematical set operations
  • Use lists when:
    • Order matters
    • You need index access
    • Duplicates are allowed
    • You need to modify elements by position

Practical Use Cases

4

Real-World Applications

Sets are used in many practical scenarios in Python programming.

# 1. Removing duplicates from a list
original = [1, 2, 2, 3, 3, 3, 4, 5, 5]
unique = list(set(original))
print(unique)  # [1, 2, 3, 4, 5] (order may vary)

# 2. Finding common elements (intersection)
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
common = set1 & set2
print(common)  # {4, 5}

# 3. Finding differences
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
difference = set1 - set2
print(difference)  # {1, 2, 3}

# 4. Finding unique elements (symmetric difference)
unique_items = set1 ^ set2
print(unique_items)  # {1, 2, 3, 6, 7, 8}

# 5. Checking for duplicates in a collection
items = [1, 2, 3, 4, 5, 1, 2]
has_duplicates = len(items) != len(set(items))
print(has_duplicates)  # True

# 6. Membership testing
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits)   # True
print("grape" in fruits)   # False

# 7. Counting unique words
text = "the cat in the hat with the cat and the hat"
words = text.split()
unique_words = set(words)
print(f"Total words: {len(words)}")
print(f"Unique words: {len(unique_words)}")

Common Mistakes

5

Pitfalls and Solutions

Mistake 1: Using {} to Create an Empty Set

# WRONG — creates a dictionary
empty = {}
print(type(empty))  # <class 'dict'>

# CORRECT — use set()
empty = set()
print(type(empty))  # <class 'set'>

Mistake 2: Adding Unhashable Types

# WRONG — raises TypeError
my_set = {1, 2, 3}
# my_set.add([4, 5])  # TypeError: unhashable type: 'list'

# CORRECT — use immutable types
my_set.add((4, 5))  # Tuple is hashable

Mistake 3: Assuming Set Order

# WRONG — sets are unordered
my_set = {1, 2, 3, 4, 5}
# print(my_set[0])  # TypeError

# CORRECT — use lists if order matters
my_list = [1, 2, 3, 4, 5]
print(my_list[0])  # 1

Quick Check: What is the most common mistake with sets? (Answer: Using {} to create an empty set — it creates a dictionary)

Interactive Editor

Experiment with sets in the interactive editor below. Modify the code and observe the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
SET PRACTICE
========================================

1. CREATING SETS
Fruits: {'apple', 'banana', 'cherry'}
Numbers: {1, 2, 3, 4, 5}
Empty set: set()
Type of empty_set: <class 'set'>

2. UNIQUENESS
Set with duplicates: {1, 2, 3, 4}

3. ADDING AND REMOVING
After adding mango: {'apple', 'banana', 'cherry', 'mango'}
After removing banana: {'apple', 'cherry', 'mango'}

4. SET OPERATIONS
Set1: {1, 2, 3, 4, 5}
Set2: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (set1 - set2): {1, 2, 3}

5. REMOVING DUPLICATES
Original: [1, 2, 2, 3, 3, 3, 4, 5, 5]
Unique: [1, 2, 3, 4, 5]

Set practice complete!
🏆

Certificate of Completion

You have completed the Python Set tutorial. You now understand set creation, uniqueness, characteristics, and the key differences between sets and lists.

Quick Quiz — Test Your Knowledge

Let's see what you've learned about sets:

1. What is the correct way to create an empty set?
2. Which of the following is true about sets?
3. Can a set contain a list as an element?
4. Which operation returns the intersection of two sets?
5. How do you remove duplicates from a list using sets?

Frequently Asked Questions

What is a set in Python? ▼

A set is an unordered, mutable collection of unique elements in Python. Sets are defined using curly braces {} and automatically remove duplicates.

What is the difference between a set and a list? ▼

Sets are unordered, store only unique elements, and cannot be indexed. Lists are ordered, allow duplicates, and support index access. Sets are faster for membership testing.

How do I create an empty set? ▼

Use set() to create an empty set. Using {} creates an empty dictionary, not a set.

Can a set contain mutable elements? ▼

No, sets can only contain immutable (hashable) elements like numbers, strings, and tuples. Lists and dictionaries cannot be stored in sets.

Are sets ordered in Python? ▼

No, sets are unordered. The order of elements is not guaranteed and may vary between runs. If order matters, use a list or a dictionary.

How do I remove duplicates from a list? ▼

Convert the list to a set and back: unique_list = list(set(my_list)). Note that this will change the order of elements.

Where to Go From Here

After mastering sets, consider exploring these related topics:

Access Set Elements

Learn how to access and iterate through set elements.

Learn More →

Set Methods

Explore built-in set methods and operations.

Learn More →

List vs Set

Detailed comparison of lists and sets.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • Python Data Types Interview Questions
  • Top PL SQL Interview Questions
Previous: Tuple Assignments Next: Access Set Elements →