Nearby lessons

61 of 108

Python - Set Data Structure

Introduction to Set

If we want to represent a group of unique values as a single entity, then we should use a Set.

A Set is one of Python's built-in collection data types.

It automatically removes duplicate elements and stores only unique values.

Characteristics of Set

A Set has the following characteristics:

  • Duplicate elements are not allowed.
  • Insertion order is not preserved.
  • We can sort the elements.
  • Indexing is not supported.
  • Slicing is not supported.
  • Heterogeneous elements are allowed.
  • Set objects are mutable.
  • Mathematical operations like Union, Intersection, Difference and Symmetric Difference are supported.

Features of Set

1. Duplicate Elements are Not Allowed

A Set stores only unique values.

If duplicate values are provided, Python automatically removes them.

2. Insertion Order is Not Preserved

A Set does not maintain the order in which elements are inserted.

Therefore, while printing a set, the output order may be different from the insertion order.

3. Heterogeneous Elements are Allowed

A Set can store different types of data together.

4. Set is Mutable

After creating a Set, we can add, remove and update elements.

5. Mathematical Operations are Supported

Python supports mathematical operations such as Union, Intersection, Difference and Symmetric Difference on Set objects.

Example - Heterogeneous Set

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 'A', 20.5, True}

Explanation

The above Set contains different types of values:

  • Integer
  • String
  • Float
  • Boolean

Hence, heterogeneous elements are allowed in a Set.

Representation of Set

A Set is represented using curly braces {}.

Each element is separated by a comma (,).

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Creating Set Objects

There are different ways to create a Set in Python.

Method 1 - Creating a Set with Known Elements

If the elements are already known, we can create a Set directly using curly braces.

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{40, 10, 20, 30}

Important Note

Since insertion order is not preserved, the output order may be different each time the program runs.

Method 2 - Using set() Function

We can also create a Set by using the set() function.

The argument can be any iterable object such as a List, Tuple, Range or String.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Create Set from List

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{40, 10, 20, 30}

Explanation

The duplicate values (10 and 20) are removed automatically.

Only unique values are stored in the Set.

Example 2 - Create Set Using range()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{0, 1, 2, 3, 4}

Creating an Empty Set

While creating an empty Set, we must use the set() function.

Using empty curly braces creates an empty Dictionary, not a Set.

Incorrect Method

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{}

Explanation

The expression {} creates an empty Dictionary.

It does not create an empty Set.

Correct Method

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
set()

Comparison - {} vs set()

Expression Creates
{} Empty Dictionary
set() Empty Set

Summary

Topic Description
Set Collection of unique values
Duplicate Elements Not Allowed
Insertion Order Not Preserved
Heterogeneous Elements Allowed
Mutable Yes
Indexing Not Supported
Slicing Not Supported
Mathematical Operations Supported
Representation Curly Braces {}
Empty Set Created using set()

Important Notes

  • A Set stores only unique values.
  • Duplicate elements are removed automatically.
  • Insertion order is not preserved.
  • Heterogeneous elements are allowed.
  • Set objects are mutable.
  • Mathematical operations such as Union, Intersection, Difference and Symmetric Difference are supported.
  • Sets are represented using curly braces {}.
  • The set() function creates a Set from any iterable object.
  • {} creates an empty Dictionary.
  • To create an empty Set, always use set().

Important Set Methods (Part A)

Python provides several built-in methods to modify a Set.

In this part, we will learn the following methods:

  • add()
  • update()
  • copy()
  • pop()

add() Method

The add() method is used to add a single element to a Set.

If the element already exists, Python does not add it again because duplicate values are not allowed.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Add a Single Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{40, 10, 20, 30}

Explanation

The value 40 is added to the Set.

Since a Set does not preserve insertion order, the output order may be different.

Example 2 - Add Duplicate Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 20, 30}

Explanation

The value 20 already exists in the Set.

Therefore, no duplicate element is added.

Important Points - add()

  • Adds only one element.
  • Duplicate elements are ignored automatically.
  • The original Set is modified.

update() Method

The update() method is used to add multiple elements to a Set.

The arguments passed to update() must be iterable objects.

Examples of iterable objects are:

  • List
  • Tuple
  • Range
  • Set
  • String

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Update Using List and Range

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}

Explanation

The elements from the List and Range are added to the Set.

Duplicate values are removed automatically.

The display order may vary because Sets are unordered.

Difference Between add() and update()

add() update()
Adds one element. Adds multiple elements.
Accepts only one argument. Accepts one or more iterable objects.
The argument can be a single element. Arguments must be iterable objects.

Valid Example - add()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 20, 30}

Invalid Example - add()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
TypeError: add() takes exactly one argument (3 given)

Invalid Example - update()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
TypeError: 'int' object is not iterable

Valid Example - update()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20}

copy() Method

The copy() method returns a copy of the Set.

The copied Set is a new object containing the same elements.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 20, 30}

Important Point - copy()

The copy() method creates a new Set object.

The original Set remains unchanged.

pop() Method

The pop() method removes and returns a random element from the Set.

Since Sets do not preserve insertion order, we cannot predict which element will be removed.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{40, 10, 20, 30}

40

{10, 20, 30}

Explanation

The removed element is random.

Different executions may remove different elements because Sets are unordered.

Important Points - pop()

  • Removes one random element.
  • Returns the removed element.
  • The removed element is not fixed.
  • The output may vary each time the program runs.

Summary

Method Description
add(x) Adds one element.
update(x, y...) Adds elements from one or more iterable objects.
copy() Returns a copy of the Set.
pop() Removes and returns a random element.

Important Notes

  • add() adds only one element.
  • update() adds multiple elements from iterable objects.
  • update() accepts only iterable objects.
  • add() accepts only one argument.
  • copy() creates a cloned copy of the Set.
  • pop() removes and returns a random element.
  • The order of elements in a Set may vary.
  • Duplicate elements are ignored automatically while using add() and update().

Important Set Methods (Part B)

In this part, we will learn the following Set methods:

  • remove()
  • discard()

Both methods are used to remove elements from a Set, but they behave differently when the specified element is not available.

remove() Method

The remove() method removes the specified element from a Set.

If the specified element is not present, Python raises a KeyError.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Remove an Existing Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{20, 30}

Explanation

The element 10 is present in the Set.

Therefore, it is removed successfully.

Since Sets do not preserve insertion order, the output order may vary.

Example 2 - Remove a Non-Existing Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
KeyError: 40

Explanation

The element 40 is not available in the Set.

Therefore, Python raises a KeyError.

Important Points - remove()

  • Removes the specified element.
  • Raises KeyError if the element is not present.
  • Best when you are sure that the element exists in the Set.

discard() Method

The discard() method also removes the specified element from a Set.

If the element is not present, no exception is raised.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Remove an Existing Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 30}

Explanation

The specified element is removed successfully.

No value is returned by the discard() method.

Example 2 - Remove a Non-Existing Element

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 20, 30}

Explanation

The element 40 is not available in the Set.

The discard() method does nothing.

No exception is raised.

Important Points - discard()

  • Removes the specified element.
  • If the element is not present, no error is raised.
  • Best when you are not sure whether the element exists.

Difference Between remove() and discard()

remove() discard()
Removes the specified element. Removes the specified element.
Raises KeyError if the element is not present. Does not raise any error if the element is not present.
Best when the element definitely exists. Best when the element may or may not exist.

Comparison Table

Feature remove() discard()
Removes Element Yes Yes
Raises Error Yes (KeyError) No
Safe for Unknown Elements No Yes
Returns Value No No

Real World Usage

These methods are commonly used in:

  • Student attendance systems.
  • Inventory management.
  • User permission management.
  • Removing duplicate records.
  • Data cleaning applications.

Important Notes

  • remove() removes the specified element.
  • If the element is not present, remove() raises a KeyError.
  • discard() also removes the specified element.
  • If the element is not present, discard() does nothing.
  • Use remove() when the element is guaranteed to exist.
  • Use discard() when the element may or may not exist.
  • Both methods modify the original Set.
  • Neither method returns the removed element.

Quick Summary

Method Description
remove(x) Removes the specified element. Raises KeyError if not found.
discard(x) Removes the specified element. No error if not found.

clear() Method

The clear() method removes all elements from the Set.

After calling this method, the Set becomes empty.

The Set object still exists, but it contains no elements.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Remove All Elements

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Before clear(): {40, 10, 20, 30}

After clear(): set()

Explanation

The clear() method removes every element from the Set.

The Set object is not deleted.

Only its contents are removed.

Example 2 - Verify Set Exists

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
0

Explanation

Even after using clear(), the variable still refers to a Set object.

Its length becomes 0.

Important Points - clear()

  • Removes all elements from the Set.
  • The Set object is not deleted.
  • Returns None.
  • The resulting Set becomes empty.

Difference Between pop(), remove(), discard() and clear()

Method Purpose Raises Error?
pop() Removes one random element. No
remove() Removes a specified element. Yes, if the element is not present.
discard() Removes a specified element. No
clear() Removes all elements. No

Comparison Table

Method Removes Returns Value
pop() One random element Yes
remove() Specified element No
discard() Specified element No
clear() All elements No

When to Use Each Method

Situation Recommended Method
Remove any one element. pop()
Remove a known element. remove()
Remove an element that may or may not exist. discard()
Remove all elements. clear()

Real World Usage

These methods are commonly used in:

  • Removing inactive users.
  • Clearing cache data.
  • Inventory management systems.
  • Attendance management.
  • Data cleaning applications.

Summary of Set Methods

Method Description
add(x) Adds one element.
update(x) Adds multiple elements.
copy() Creates a copy of the Set.
pop() Removes one random element.
remove(x) Removes the specified element.
discard(x) Removes the specified element without raising an error.
clear() Removes all elements.

Important Notes

  • clear() removes every element from the Set.
  • The Set object still exists after calling clear().
  • pop() removes a random element.
  • remove() raises KeyError if the element does not exist.
  • discard() does not raise an exception if the element does not exist.
  • All these methods modify the original Set.
  • Only pop() returns the removed element.
  • clear() is useful when you want to reuse an empty Set.

Quick Summary

Method Purpose
pop() Remove one random element.
remove() Remove a specific element.
discard() Remove a specific element safely.
clear() Remove all elements.

Mathematical Operations on Set

One of the biggest advantages of a Set is that it supports mathematical set operations.

These operations are useful for comparing two or more sets and finding common or unique elements.

Python supports the following mathematical operations:

  • union()
  • intersection()
  • difference()
  • symmetric_difference()

union() Method

The union() method returns a new Set containing all unique elements from both Sets.

Duplicate elements are automatically removed.

The original Sets are not modified.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - union()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 20, 30, 40, 50}

Example 2 - Union Operator (|)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{1, 2, 3, 4, 5}

Important Notes - union()

  • Returns a new Set.
  • Duplicate elements are removed.
  • The original Sets remain unchanged.

intersection() Method

The intersection() method returns only the common elements available in both Sets.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - intersection()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{30, 40}

Example 2 - Intersection Operator (&)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{2, 3}

Important Notes - intersection()

  • Returns only common elements.
  • Returns a new Set.
  • The original Sets are not modified.

difference() Method

The difference() method returns elements that are present in the first Set but not in the second Set.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - difference()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 20}

Example 2 - Difference Operator (-)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{1, 2}

Important Notes - difference()

  • Returns elements present only in the first Set.
  • The operation is not symmetric.
  • The original Sets remain unchanged.

symmetric_difference() Method

The symmetric_difference() method returns elements that are present in either Set but not in both.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - symmetric_difference()

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{10, 20, 40, 50}

Example 2 - Symmetric Difference Operator (^)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{1, 2, 4, 5}

Important Notes - symmetric_difference()

  • Returns elements that are not common.
  • Common elements are removed.
  • The original Sets remain unchanged.

Membership Operators

Membership operators are used to check whether an element exists in a Set.

Python provides two membership operators:

  • in
  • not in

Example - Membership Operators

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
True

False

True

Comparison of Mathematical Operations

Method Operator Returns
union() | All unique elements
intersection() & Common elements
difference() - Elements only in first Set
symmetric_difference() ^ Non-common elements

Real World Usage

Mathematical Set operations are commonly used in:

  • Student attendance comparison.
  • Database record matching.
  • Product recommendation systems.
  • Finding common friends in social networks.
  • Data analysis and reporting.

Important Notes

  • union() returns all unique elements.
  • intersection() returns only common elements.
  • difference() returns elements present only in the first Set.
  • symmetric_difference() returns elements that are not common.
  • The operators |, &, - and ^ perform the same operations as their respective methods.
  • Membership operators in and not in are used to check the presence of elements.
  • All mathematical operations return new Set objects.
  • The original Sets remain unchanged.

Quick Summary

Operation Result
Union All unique elements
Intersection Common elements
Difference Elements only in first Set
Symmetric Difference Elements except common ones
Membership Checks whether an element exists

Set Comprehension

Python supports Set Comprehension, which provides a short and simple way to create a Set.

It is similar to List Comprehension, but it creates a Set instead of a List.

Set Comprehension automatically removes duplicate values because a Set stores only unique elements.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Create a Set

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{1, 2, 3, 4, 5}

Example 2 - Square of Numbers

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{1, 4, 9, 16, 25}

Example 3 - Even Numbers

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{2, 4, 6, 8, 10}

Example 4 - Odd Numbers

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{1, 3, 5, 7, 9}

Example 5 - Remove Duplicate Values

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{40, 10, 20, 30}

Example 6 - Convert String to Uppercase

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
{'PYTHON', 'JAVA', 'HTML'}

Advantages of Set Comprehension

  • Requires less code.
  • Easy to understand.
  • Creates Sets quickly.
  • Automatically removes duplicate values.
  • Supports conditions using if.

Why Indexing is Not Supported?

Indexing depends on the position of elements.

Since a Set does not preserve insertion order, every element does not have a fixed position.

Therefore, indexing is not supported.

Example - Indexing

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
TypeError: 'set' object is not subscriptable

Why Slicing is Not Supported?

Slicing is based on indexes.

Since indexing is not available for Sets, slicing is also not supported.

Example - Slicing

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
TypeError: 'set' object is not subscriptable

Difference Between List, Tuple and Set

Feature List Tuple Set
Order Preserved Yes Yes No
Duplicate Elements Allowed Allowed Not Allowed
Mutable Yes No Yes
Indexing Supported Supported Not Supported
Slicing Supported Supported Not Supported
Representation [] () {}

Complete Summary

Topic Description
Set Collection of unique values.
Duplicate Values Automatically removed.
Insertion Order Not preserved.
Mutable Yes.
Indexing Not supported.
Slicing Not supported.
Mathematical Operations Union, Intersection, Difference and Symmetric Difference.
Comprehension Supported.
Representation Curly braces {}
Best Use Store unique values.

Important Notes

  • Set stores only unique values.
  • Duplicate elements are automatically removed.
  • Insertion order is not preserved.
  • Set objects are mutable.
  • Indexing and slicing are not supported.
  • Set Comprehension provides a simple way to create Sets.
  • Conditions can be used inside Set Comprehension.
  • Mathematical operations are supported.
  • Membership operators in and not in are supported.
  • Sets are best when only unique values are required.

Quick Summary

Feature Set
Duplicates Not Allowed
Order Not Preserved
Mutable Yes
Indexing No
Slicing No
Mathematical Operations Supported
Comprehension Supported
Best For Unique Values

🧠 Test Your Knowledge

48 Questions

Progress: 0 / 48
Keep Going!Python - Dictionary Collection