Nearby lessons

66 of 159

Python - Sets

📌 What You Will Learn
  • Understand what a set is and how it stores only unique values
  • Create sets using set() and modify them with add(), update() and remove()
  • Remove elements with remove(), discard(), pop() and clear()
  • Apply mathematical operations like union, intersection, difference and symmetric difference
  • Use membership operators with sets
  • Write set comprehensions and compare sets with lists and tuples

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

🐍Code Cell
1s = {10, "A", 20.5, True}
2 
3print(s)
Output
{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

🐍Code Cell
1s = {10, 20, 30, 40}
Output
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

🐍Code Cell
1s = {10, 20, 30, 40}
2 
3print(s)
4 
5print(type(s))
Output
{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

🐍Code Cell
1set(any_iterable)
Output
No output captured.

Example 1 - Create Set from List

🐍Code Cell
1l = [10, 20, 30, 40, 10, 20, 10]
2 
3s = set(l)
4 
5print(s)
Output
{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()

🐍Code Cell
1s = set(range(5))
2 
3print(s)
Output
{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

🐍Code Cell
1s = {}
2 
3print(s)
4 
5print(type(s))
Output
{}

Explanation

The expression {} creates an empty Dictionary.

It does not create an empty Set.

Correct Method

🐍Code Cell
1s = set()
2 
3print(s)
4 
5print(type(s))
Output
set()

Comparison - {} vs set()

Expression Creates
{} Empty Dictionary
set() Empty 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

🐍Code Cell
1set_name.add(element)
Output
No output captured.

Example 1 - Add a Single Element

🐍Code Cell
1s = {10, 20, 30}
2 
3s.add(40)
4 
5print(s)
Output
{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

🐍Code Cell
1s = {10, 20, 30}
2 
3s.add(20)
4 
5print(s)
Output
{10, 20, 30}

Explanation

The value 20 already exists in the Set.

Therefore, no duplicate element is added.

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

🐍Code Cell
1set_name.update(iterable1)
2 
3set_name.update(iterable1, iterable2, ...)
Output
No output captured.

Example 1 - Update Using List and Range

🐍Code Cell
1s = {10, 20, 30}
2 
3l = [40, 50, 60, 10]
4 
5s.update(l, range(5))
6 
7print(s)
Output
{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()

🐍Code Cell
1s = {10, 20}
2 
3s.add(30)
4 
5print(s)
Output
{10, 20, 30}

Invalid Example - add()

🐍Code Cell
1s = {10, 20}
2 
3s.add(30, 40, 50)
Output
TypeError: add() takes exactly one argument (3 given)

Invalid Example - update()

🐍Code Cell
1s = {10, 20}
2 
3s.update(30)
Output
TypeError: 'int' object is not iterable

Valid Example - update()

🐍Code Cell
1s = {10, 20}
2 
3s.update(range(1, 10, 2), range(0, 10, 2))
4 
5print(s)
Output
{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

🐍Code Cell
1new_set = set_name.copy()
Output
No output captured.

Example

🐍Code Cell
1s = {10, 20, 30}
2 
3s1 = s.copy()
4 
5print(s1)
Output
{10, 20, 30}

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

🐍Code Cell
1set_name.pop()
Output
No output captured.

Example

🐍Code Cell
1s = {40, 10, 30, 20}
2 
3print(s)
4 
5print(s.pop())
6 
7print(s)
Output
{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 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

🐍Code Cell
1set_name.remove(element)
Output
No output captured.

Example 1 - Remove an Existing Element

🐍Code Cell
1s = {10, 20, 30}
2 
3s.remove(10)
4 
5print(s)
Output
{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

🐍Code Cell
1s = {10, 20, 30}
2 
3s.remove(40)
Output
KeyError: 40

Explanation

The element 40 is not available in the Set.

Therefore, Python raises a KeyError.

discard() Method

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

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

Syntax

🐍Code Cell
1set_name.discard(element)
Output
No output captured.

Example 1 - Remove an Existing Element

🐍Code Cell
1s = {10, 20, 30}
2 
3s.discard(20)
4 
5print(s)
Output
{10, 30}

Explanation

The specified element is removed successfully.

No value is returned by the discard() method.

Example 2 - Remove a Non-Existing Element

🐍Code Cell
1s = {10, 20, 30}
2 
3s.discard(40)
4 
5print(s)
Output
{10, 20, 30}

Explanation

The element 40 is not available in the Set.

The discard() method does nothing.

No exception is raised.

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.

Real World Usage

These methods are commonly used in:

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

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

🐍Code Cell
1set_name.clear()
Output
No output captured.

Example 1 - Remove All Elements

🐍Code Cell
1s = {10, 20, 30, 40}
2 
3print("Before clear():", s)
4 
5s.clear()
6 
7print("After clear():", s)
Output
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

🐍Code Cell
1s = {1, 2, 3}
2 
3s.clear()
4 
5print(type(s))
6 
7print(len(s))
Output
0

Explanation

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

Its length becomes 0.

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

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.

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

🐍Code Cell
1set3 = set1.union(set2)
2 
3# or
4 
5set3 = set1 | set2
Output
No output captured.

Example 1 - union()

🐍Code Cell
1s1 = {10, 20, 30}
2 
3s2 = {30, 40, 50}
4 
5print(s1.union(s2))
Output
{10, 20, 30, 40, 50}

Example 2 - Union Operator (|)

🐍Code Cell
1s1 = {1, 2, 3}
2 
3s2 = {3, 4, 5}
4 
5print(s1 | s2)
Output
{1, 2, 3, 4, 5}

intersection() Method

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

Syntax

🐍Code Cell
1set3 = set1.intersection(set2)
2 
3# or
4 
5set3 = set1 & set2
Output
No output captured.

Example 1 - intersection()

🐍Code Cell
1s1 = {10, 20, 30, 40}
2 
3s2 = {30, 40, 50, 60}
4 
5print(s1.intersection(s2))
Output
{30, 40}

Example 2 - Intersection Operator (&)

🐍Code Cell
1s1 = {1, 2, 3}
2 
3s2 = {2, 3, 4}
4 
5print(s1 & s2)
Output
{2, 3}

difference() Method

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

Syntax

🐍Code Cell
1set3 = set1.difference(set2)
2 
3# or
4 
5set3 = set1 - set2
Output
No output captured.

Example 1 - difference()

🐍Code Cell
1s1 = {10, 20, 30, 40}
2 
3s2 = {30, 40, 50}
4 
5print(s1.difference(s2))
Output
{10, 20}

Example 2 - Difference Operator (-)

🐍Code Cell
1s1 = {1, 2, 3, 4}
2 
3s2 = {3, 4, 5}
4 
5print(s1 - s2)
Output
{1, 2}

symmetric_difference() Method

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

Syntax

🐍Code Cell
1set3 = set1.symmetric_difference(set2)
2 
3# or
4 
5set3 = set1 ^ set2
Output
No output captured.

Example 1 - symmetric_difference()

🐍Code Cell
1s1 = {10, 20, 30}
2 
3s2 = {30, 40, 50}
4 
5print(s1.symmetric_difference(s2))
Output
{10, 20, 40, 50}

Example 2 - Symmetric Difference Operator (^)

🐍Code Cell
1s1 = {1, 2, 3}
2 
3s2 = {3, 4, 5}
4 
5print(s1 ^ s2)
Output
{1, 2, 4, 5}

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

🐍Code Cell
1s = {10, 20, 30}
2 
3print(20 in s)
4 
5print(40 in s)
6 
7print(50 not in s)
Output
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.

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

🐍Code Cell
1{expression for variable in iterable}
Output
No output captured.

Example 1 - Create a Set

🐍Code Cell
1s = {x for x in range(1, 6)}
2 
3print(s)
Output
{1, 2, 3, 4, 5}

Example 2 - Square of Numbers

🐍Code Cell
1s = {x*x for x in range(1, 6)}
2 
3print(s)
Output
{1, 4, 9, 16, 25}

Example 3 - Even Numbers

🐍Code Cell
1s = {x for x in range(1, 11) if x % 2 == 0}
2 
3print(s)
Output
{2, 4, 6, 8, 10}

Example 4 - Odd Numbers

🐍Code Cell
1s = {x for x in range(1, 11) if x % 2 != 0}
2 
3print(s)
Output
{1, 3, 5, 7, 9}

Example 5 - Remove Duplicate Values

🐍Code Cell
1numbers = [10, 20, 10, 30, 20, 40]
2 
3s = {x for x in numbers}
4 
5print(s)
Output
{40, 10, 20, 30}

Example 6 - Convert String to Uppercase

🐍Code Cell
1languages = {"python", "java", "html"}
2 
3upper = {lang.upper() for lang in languages}
4 
5print(upper)
Output
{'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

🐍Code Cell
1s = {10, 20, 30}
2 
3print(s[0])
Output
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

🐍Code Cell
1s = {10, 20, 30, 40}
2 
3print(s[1:3])
Output
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 [] () {}
📝 Key Takeaways
  • A set stores unique values and automatically removes duplicates
  • Sets do not support indexing or slicing
  • add() and update() add elements while remove(), discard(), pop() and clear() remove them
  • Union (|), intersection (&), difference (-) and symmetric difference (^) compare sets
  • Set comprehensions build sets in one expression

🧠 Test Your Knowledge

48 Questions
Progress: 0 / 48