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: Methods and Operations

Python Set Methods - Complete Guide

Learn how to use Python set methods including add, remove, discard, pop, union, intersection, and difference.

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 Set Methods
  • add() — Add Elements
  • remove() — Delete by Value
  • discard() — Safe Removal
  • pop() — Remove and Return
  • clear() — Remove All
  • union() — Combine Sets
  • intersection() — Common Elements
  • difference() — Elements in One Set Only
  • symmetric_difference() — Elements in Either Set
  • update() — In-Place Union
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • add() — add elements to a set
  • remove() — remove elements by value
  • discard() — safely remove elements
  • pop() — remove and return arbitrary element
  • clear() — remove all elements
  • union() — combine sets
  • intersection() — common elements
  • difference() — elements in one set only
  • symmetric_difference() — elements in either set
  • update() — in-place union

Introduction to Set Methods

Python sets provide a rich collection of methods for manipulating set data. These methods can be grouped into several categories:

  • Adding methods: add(), update()
  • Removing methods: remove(), discard(), pop(), clear()
  • Set operations: union(), intersection(), difference(), symmetric_difference()
  • Set relationships: issubset(), issuperset(), isdisjoint()

Most set methods modify the set in place, meaning they change the original set rather than creating a new one.

💡 Key concept: Many set methods have both in-place versions (modifying the original set) and operator equivalents (|, &, -, ^) that return new sets.

add() — Add Elements

1

Adding a Single Element

The add() method adds a single element to the set. If the element already exists, it has no effect.

# Basic usage
fruits = {"apple", "banana", "cherry"}
print(fruits)  # {'apple', 'banana', 'cherry'}

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

# Adding an existing element (no effect)
fruits.add("apple")
print(fruits)  # {'apple', 'banana', 'cherry', 'mango'}

# Adding different data types
numbers = {1, 2, 3}
numbers.add(4)        # Integer
numbers.add("five")   # String
numbers.add((6, 7))   # Tuple
print(numbers)  # {1, 2, 3, 4, 'five', (6, 7)}

# Adding in a loop
squares = set()
for i in range(5):
    squares.add(i ** 2)
print(squares)  # {0, 1, 4, 9, 16}

Characteristics:

  • Adds a single element to the set
  • Modifies the set in place (returns None)
  • Has no effect if the element already exists
  • Element must be hashable (immutable)
  • Time complexity: O(1) on average

Quick Check: What happens if you add an element that already exists in the set? (Answer: Nothing — the set remains unchanged)

remove() — Delete by Value

2

Removing a Specific Element

The remove() method removes a specified element from the set. If the element is not found, it raises a KeyError.

# Basic usage
fruits = {"apple", "banana", "cherry", "mango"}
print(fruits)  # {'apple', 'banana', 'cherry', 'mango'}

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

# Attempting to remove a non-existent element
# fruits.remove("grape")  # KeyError: 'grape'

# Safe approach — check first
if "grape" in fruits:
    fruits.remove("grape")
else:
    print("'grape' not in set")

# Removing in a loop
numbers = {1, 2, 3, 4, 5, 6}
for num in list(numbers):  # Iterate over a copy
    if num % 2 == 0:
        numbers.remove(num)
print(numbers)  # {1, 3, 5}

Characteristics:

  • Removes the specified element
  • Raises KeyError if the element is not found
  • Modifies the set in place
  • Time complexity: O(1) on average

Quick Check: What happens if you try to remove an element that doesn't exist? (Answer: KeyError is raised)

discard() — Safe Removal

3

Removing Without Raising Errors

The discard() method removes a specified element from the set. Unlike remove(), it does nothing if the element is not found.

# Basic usage
fruits = {"apple", "banana", "cherry", "mango"}
print(fruits)  # {'apple', 'banana', 'cherry', 'mango'}

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

# Discarding a non-existent element (no error)
fruits.discard("grape")
print(fruits)  # {'apple', 'cherry', 'mango'}

# Discarding in a loop
numbers = {1, 2, 3, 4, 5, 6}
for num in list(numbers):
    if num % 2 == 0:
        numbers.discard(num)
print(numbers)  # {1, 3, 5}

Characteristics:

  • Removes the specified element if present
  • Does nothing if the element is not found
  • No error is raised
  • Modifies the set in place
  • Time complexity: O(1) on average

Quick Check: What is the difference between remove() and discard()? (Answer: discard() does nothing if the element is not found; remove() raises KeyError)

pop() — Remove and Return

4

Removing an Arbitrary Element

The pop() method removes and returns an arbitrary element from the set. Since sets are unordered, you cannot predict which element will be removed.

# Basic usage
fruits = {"apple", "banana", "cherry", "mango"}
print(f"Original: {fruits}")

removed = fruits.pop()
print(f"Removed: {removed}")
print(f"After pop: {fruits}")

# Popping in a loop (removes all elements)
numbers = {1, 2, 3, 4, 5}
while numbers:
    element = numbers.pop()
    print(f"Removed: {element}")

print(f"Empty set: {numbers}")

# Safe usage — check before popping
fruits = {"apple", "banana", "cherry"}
if fruits:
    element = fruits.pop()
    print(f"Removed: {element}")
else:
    print("Set is empty")

# pop() cannot be called with an argument
# fruits.pop("apple")  # TypeError: set.pop() takes no arguments (1 given)

Characteristics:

  • Removes and returns an arbitrary element
  • Raises KeyError if the set is empty
  • Modifies the set in place
  • Time complexity: O(1) on average
  • Useful for processing all elements

Quick Check: What happens if you call pop() on an empty set? (Answer: KeyError is raised)

clear() — Remove All

5

Removing All Elements

The clear() method removes all elements from the set, leaving it empty.

# Basic usage
fruits = {"apple", "banana", "cherry", "mango"}
print(f"Before clear: {fruits}")

fruits.clear()
print(f"After clear: {fruits}")  # set()

# Checking if set is empty after clear
if not fruits:
    print("Set is empty")

# Clearing in a loop
numbers = {1, 2, 3, 4, 5}
for num in list(numbers):
    numbers.remove(num)
print(numbers)  # set()

# Alternative: reassign to empty set
numbers = {1, 2, 3, 4, 5}
numbers = set()  # Creates a new empty set

Characteristics:

  • Removes all elements from the set
  • Modifies the set in place
  • Time complexity: O(n)
  • Useful for resetting a set

Quick Check: What does clear() return? (Answer: None — it modifies the set in place)

union() — Combine Sets

6

Combining Sets

The union() method returns a new set containing all elements from the original set and the specified set(s). The | operator provides the same functionality.

# Basic usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Using union() method
result = set1.union(set2)
print(result)  # {1, 2, 3, 4, 5, 6, 7, 8}

# Using operator
result = set1 | set2
print(result)  # {1, 2, 3, 4, 5, 6, 7, 8}

# Original sets unchanged
print(set1)  # {1, 2, 3, 4, 5}
print(set2)  # {4, 5, 6, 7, 8}

# Union with multiple sets
set3 = {7, 8, 9, 10}
result = set1.union(set2, set3)
print(result)  # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

# Union with a list (any iterable)
list1 = [11, 12, 13]
result = set1.union(list1)
print(result)  # {1, 2, 3, 4, 5, 11, 12, 13}

Characteristics:

  • Returns a new set (does not modify original)
  • Accepts multiple iterables as arguments
  • Operator equivalent: |
  • Time complexity: O(len(s) + len(t))

Quick Check: Does union() modify the original set? (Answer: No — it returns a new set)

intersection() — Common Elements

7

Finding Common Elements

The intersection() method returns a new set containing elements that are present in both the original set and the specified set(s). The & operator provides the same functionality.

# Basic usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Using intersection() method
result = set1.intersection(set2)
print(result)  # {4, 5}

# Using operator
result = set1 & set2
print(result)  # {4, 5}

# Intersection with multiple sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
set3 = {4, 5, 8, 9, 10}
result = set1.intersection(set2, set3)
print(result)  # {4, 5}

# Intersection with a list
list1 = [3, 4, 5]
result = set1.intersection(list1)
print(result)  # {3, 4, 5}

Characteristics:

  • Returns a new set (does not modify original)
  • Accepts multiple iterables as arguments
  • Operator equivalent: &
  • Time complexity: O(min(len(s), len(t)))

Quick Check: Which operation returns elements common to both sets? (Answer: intersection() or &)

difference() — Elements in One Set Only

8

Finding Elements Unique to One Set

The difference() method returns a new set containing elements that are in the original set but not in the specified set(s). The - operator provides the same functionality.

# Basic usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Using difference() method
result = set1.difference(set2)
print(result)  # {1, 2, 3}

# Using operator
result = set1 - set2
print(result)  # {1, 2, 3}

# Difference with multiple sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5}
set3 = {5, 6, 7}
result = set1.difference(set2, set3)
print(result)  # {1, 2}

# Difference with a list
list1 = [3, 4, 5]
result = set1.difference(list1)
print(result)  # {1, 2}

Characteristics:

  • Returns a new set (does not modify original)
  • Accepts multiple iterables as arguments
  • Operator equivalent: -
  • Time complexity: O(len(s))

Quick Check: What does set1 - set2 return? (Answer: Elements in set1 but not in set2)

symmetric_difference() — Elements in Either Set

9

Finding Elements in Either Set (Not Both)

The symmetric_difference() method returns a new set containing elements that are in either the original set or the specified set, but not in both. The ^ operator provides the same functionality.

# Basic usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Using symmetric_difference() method
result = set1.symmetric_difference(set2)
print(result)  # {1, 2, 3, 6, 7, 8}

# Using operator
result = set1 ^ set2
print(result)  # {1, 2, 3, 6, 7, 8}

# Symmetric difference with a list
list1 = [4, 5, 6]
result = set1.symmetric_difference(list1)
print(result)  # {1, 2, 3, 6}

Characteristics:

  • Returns a new set (does not modify original)
  • Accepts one iterable as argument
  • Operator equivalent: ^
  • Time complexity: O(len(s) + len(t))

Quick Check: What does symmetric_difference() return? (Answer: Elements in either set but not in both)

update() — In-Place Union

10

Adding Multiple Elements In Place

The update() method adds all elements from another iterable to the set. It modifies the set in place. This is the in-place version of union().

# Basic usage
set1 = {1, 2, 3}
set2 = {4, 5, 6}
set1.update(set2)
print(set1)  # {1, 2, 3, 4, 5, 6}

# Updating with a list
fruits = {"apple", "banana"}
fruits.update(["cherry", "mango", "orange"])
print(fruits)  # {'apple', 'banana', 'cherry', 'mango', 'orange'}

# Updating with multiple iterables
set1 = {1, 2, 3}
set1.update([4, 5], {6, 7}, (8, 9))
print(set1)  # {1, 2, 3, 4, 5, 6, 7, 8, 9}

# Updating with a string (adds each character)
letters = {'a', 'b'}
letters.update('cd')
print(letters)  # {'a', 'b', 'c', 'd'}

Characteristics:

  • Modifies the set in place
  • Accepts multiple iterables as arguments
  • Equivalent to | operator but modifies in place
  • Time complexity: O(len(iterable))

Quick Check: What is the difference between union() and update()? (Answer: union() returns a new set; update() modifies the set in place)

Common Mistakes

11

Watch Out For These!

Mistake 1: Using remove() Without Checking Existence

# WRONG — raises KeyError if element not found
fruits = {"apple", "banana", "cherry"}
# fruits.remove("grape")  # KeyError

# CORRECT — check first
if "grape" in fruits:
    fruits.remove("grape")
else:
    print("Element not found")

# CORRECT — use discard() instead
fruits.discard("grape")  # No error

Mistake 2: Confusing update() with add()

# WRONG — add() adds the entire list as one element
fruits = {"apple", "banana"}
fruits.add(["cherry", "mango"])  # TypeError

# WRONG — using add() with multiple elements
# fruits.add("cherry", "mango")  # TypeError

# CORRECT — use update() for multiple elements
fruits.update(["cherry", "mango"])
print(fruits)  # {'apple', 'banana', 'cherry', 'mango'}

Mistake 3: Using pop() on an Empty Set

# WRONG — raises KeyError
empty_set = set()
# empty_set.pop()  # KeyError

# CORRECT — check before popping
if empty_set:
    element = empty_set.pop()
else:
    print("Set is empty")

Mistake 4: Modifying a Set While Iterating

# WRONG — modifies set during iteration
numbers = {1, 2, 3, 4, 5}
# for num in numbers:
#     if num % 2 == 0:
#         numbers.remove(num)  # RuntimeError

# CORRECT — iterate over a copy
for num in list(numbers):
    if num % 2 == 0:
        numbers.remove(num)
print(numbers)  # {1, 3, 5}

Quick Check: What is the difference between remove() and discard()? (Answer: remove() raises KeyError if not found; discard() does nothing)

Interactive Editor

Experiment with set methods directly in your browser. Modify the code and see the results in real time.

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

Fruits: {'apple', 'banana', 'cherry'}
Numbers1: {1, 2, 3, 4, 5}
Numbers2: {4, 5, 6, 7, 8}

1. ADD()
After add: {'apple', 'banana', 'cherry', 'mango'}

2. REMOVE()
After remove: {'apple', 'cherry', 'mango'}

3. DISCARD()
After discard: {'cherry', 'mango'}

4. POP()
Removed: cherry
After pop: {'mango'}

5. UNION()
Union: {1, 2, 3, 4, 5, 6, 7, 8}

6. INTERSECTION()
Intersection: {4, 5}

7. DIFFERENCE()
Difference (numbers1 - numbers2): {1, 2, 3}

8. SYMMETRIC_DIFFERENCE()
Symmetric difference: {1, 2, 3, 6, 7, 8}

9. UPDATE()
After update: {1, 2, 3, 4, 5, 9, 10}

10. CLEAR()
After clear: set()

Set methods practice complete!
🏆

Certificate of Completion

You have completed the Python Set Methods tutorial. You understand add, remove, discard, pop, clear, union, intersection, difference, symmetric_difference, and update methods.

Quick Quiz — Test Your Knowledge

Let's see what you've learned about set methods:

1. Which method adds a single element to a set?
2. What is the difference between remove() and discard()?
3. Which method removes all elements from a set?
4. Which operation returns elements common to both sets?
5. What is the difference between union() and update()?

Frequently Asked Questions

What is the difference between remove() and discard()? ▼

remove() raises a KeyError if the element is not found. discard() does nothing if the element is not found. Use discard() when you want to safely remove an element without checking if it exists.

What is the difference between union() and update()? ▼

union() returns a new set containing all elements from both sets. update() modifies the original set in place. Use union() when you need a new set; use update() when you want to modify the existing set.

What does pop() return from a set? ▼

pop() returns an arbitrary element from the set and removes it. Since sets are unordered, you cannot predict which element will be returned.

Can I use add() to add multiple elements? ▼

No, add() adds only a single element. Use update() to add multiple elements from an iterable.

What is the difference between intersection() and intersection_update()? ▼

intersection() returns a new set containing only common elements. intersection_update() modifies the original set in place, keeping only elements that are present in both sets.

Can I add a list to a set? ▼

No, lists are unhashable and cannot be added to a set. Use a tuple instead: my_set.add((1, 2, 3)).

Where to Go From Here

Now that you've mastered set methods, here are the next topics to explore:

Iterate Sets

Learn different ways to loop through sets.

Learn More →

Set Comprehension

Learn the powerful set comprehension technique.

Learn More →

List vs Set

Understand when to use lists and when to use 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: Access Set Elements Next: Iterate Set →