Nearby lessons
66 of 159Python - Sets
- 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
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
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
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
Example 1 - Create Set from List
Explanation
The duplicate values (10 and 20) are removed automatically.
Only unique values are stored in the Set.
Example 2 - Create Set Using range()
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
Explanation
The expression {} creates an empty Dictionary.
It does not create an empty Set.
Correct Method
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
Example 1 - Add a Single Element
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
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
Example 1 - Update Using List and Range
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()
Invalid Example - add()
Invalid Example - update()
Valid Example - update()
copy() Method
The copy() method returns a copy of the Set.
The copied Set is a new object containing the same elements.
Syntax
Example
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
Example
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
Example 1 - Remove an Existing Element
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
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
Example 1 - Remove an Existing Element
Explanation
The specified element is removed successfully.
No value is returned by the discard() method.
Example 2 - Remove a Non-Existing Element
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
Example 1 - Remove All Elements
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
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
Example 1 - union()
Example 2 - Union Operator (|)
intersection() Method
The intersection() method returns only the common elements available in both Sets.
Syntax
Example 1 - intersection()
Example 2 - Intersection Operator (&)
difference() Method
The difference() method returns elements that are present in the first Set but not in the second Set.
Syntax
Example 1 - difference()
Example 2 - Difference Operator (-)
symmetric_difference() Method
The symmetric_difference() method returns elements that are present in either Set but not in both.
Syntax
Example 1 - symmetric_difference()
Example 2 - Symmetric Difference Operator (^)
Membership Operators
Membership operators are used to check whether an element exists in a Set.
Python provides two membership operators:
innot in
Example - Membership Operators
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
Example 1 - Create a Set
Example 2 - Square of Numbers
Example 3 - Even Numbers
Example 4 - Odd Numbers
Example 5 - Remove Duplicate Values
Example 6 - Convert String to Uppercase
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
Why Slicing is Not Supported?
Slicing is based on indexes.
Since indexing is not available for Sets, slicing is also not supported.
Example - Slicing
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 | [] | () | {} |
- 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