USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Sets

Lesson 8/15 | Study Time: 25 Min

Sets in Python


A set in Python is an unordered collection of unique and immutable elements. It is used when you want to store multiple items, but without worrying about their order or duplicates. Sets are based on mathematical set theory and provide fast operations for checking membership, removing duplicates, and performing set-based operations. A set cannot contain lists, dictionaries, or other mutable objects, but it can store integers, floats, strings, tuples, and other immutable data types. Sets are dynamic, meaning elements can be added or removed anytime. Since they do not maintain order, indexing and slicing are not allowed. Sets are mainly used when the uniqueness of items is important and when operations like union, intersection, and difference are needed.


A set in Python is an unordered, mutable collection of unique elements. This means sets do not allow duplicate values, and the position of elements cannot be accessed using indexes because the data is stored in an unordered manner. Sets are mainly used for operations involving mathematics like union, intersection, difference, and for removing duplicates from collections. Sets are very fast for membership testing due to their internal hashing mechanism.


Set Methods used in Python:


Set methods in Python are built-in functions that help perform operations on sets efficiently. They allow you to add, remove, and update elements, as well as perform mathematical set operations. Common methods include add(), remove(), discard(), pop(), clear(), union(), intersection(), difference(), and symmetric_difference(). These methods make it easy to manipulate sets and handle unique collections of data. Understanding set methods is essential for effective data management and performing set-based operations in Python.




1. Add() Method


The add() method in Python is used to insert a single element into a set. Since sets do not allow duplicate values, adding an existing element has no effect. Sets are unordered, so the new element may appear in any position. This method is useful for dynamically building sets with unique items. Understanding add() helps in efficiently managing and updating set data.

Syntax

set_name.add(element)


Example

s = {1, 2, 3}

s.add(4)                        # Adds 4 to the set

print(s)                        # Output: {1, 2, 3, 4}


2. Update() Method


The update() method in Python adds multiple elements to a set at once from any iterable, such as a list, tuple, or another set. It inserts each element individually into the set. Duplicate values are automatically ignored, ensuring all elements remain unique. This method is useful for merging sets or adding several items efficiently. Understanding update() helps in managing and expanding sets effectively.


Syntax

set_name.update(iterable)


Example

s = {1, 2}

s.update([2, 3, 4])             # Adds 3 and 4, but ignores duplicate 2

print(s)                        # Output: {1, 2, 3, 4}


3. Remove() Method


The remove() method in Python deletes a specified element from a set. If the element is not present, it raises a KeyError. This method should be used only when you are certain that the element exists in the set. It is useful for safely removing known items. Understanding remove() helps in managing set data accurately.


Syntax

set_name.remove(element)


Example

s = {10, 20, 30}

s.remove(20)                    # Removes 20 from the set

print(s)                        # Output: {10, 30}


4. Discard() Method


The discard() method in Python removes a specified element from a set, similar to remove(). However, it does not raise an error if the element is not present and simply ignores the request. This makes it safer to use when you are unsure whether the element exists. It is useful for cleaning or updating sets without causing exceptions. Understanding discard() helps in managing sets more flexibly.


Syntax

set_name.discard(element)


Example

s = {5, 10, 15}

s.discard(10)                   # Removes 10

s.discard(20)                   # No error even though 20 is not         present  

print(s)                        # Output: {5, 15}


5. Pop() Method


The pop() method in Python removes and returns a random element from a set, since sets are unordered. You cannot specify which element will be removed. This method is useful when you want to process or remove elements randomly or gradually empty a set. It allows flexible handling of set items without relying on order. Understanding pop() helps in managing set data efficiently.


Syntax

set_name.pop()


Example

s = {1, 2, 3}

removed = s.pop()               # Removes random element

print(removed)                  # Output: may be 1, 2, or 3

print(s)                        # Remaining elements


6. Clear() Method


The clear() method in Python removes all elements from a set, leaving it empty. The set object itself still exists, but its contents are deleted. This method is useful for resetting a set without deleting the variable. It allows efficient clearing of data in a single step. Understanding clear() helps in managing and reusing set objects effectively.


Syntax

set_name.clear()


Example

s = {1, 2, 3}

s.clear()                       # Removes all elements

print(s)                        # Output: set()


7. Union() Method


The union() method in Python returns a new set containing all unique elements from two or more sets. It does not modify the original sets and ensures that duplicate values are not included. This method is useful for combining data while maintaining uniqueness. Understanding union() helps in performing efficient set operations and merging collections.


Syntax

set1.union(set2)


Example

a = {1, 2, 3}

b = {3, 4, 5}


print(a.union(b))               # Output: {1, 2, 3, 4, 5}


8. Intersection() Method


The intersection() method in Python returns a new set containing only the elements that are common to both sets. It does not modify the original sets. This method is useful for identifying shared data or overlapping elements between collections. Understanding intersection() helps in performing efficient set comparisons and data analysis.


Syntax

set1.intersection(set2)


Example

a = {1, 2, 3}

b = {2, 3, 4}


print(a.intersection(b))        # Output: {2, 3}


9. Difference() Method


The difference() method in Python returns a new set containing elements that exist in the first set but not in the second. It does not modify the original sets. This method is useful for identifying items that are unique to one set. Understanding difference() helps in comparing sets and extracting exclusive data efficiently.

Syntax

set1.difference(set2)


Example

a = {1, 2, 3, 4}

b = {3, 4}


print(a.difference(b))          # Output: {1, 2}


10. Symmetric_difference() Method


The symmetric_difference() method in Python returns a new set containing elements that are not common to the two sets. It excludes any elements that appear in both sets. This method is useful for identifying unique data across sets. Understanding symmetric_difference() helps in performing advanced set operations and comparisons efficiently.

Syntax

set1.symmetric_difference(set2)


Example

a = {1, 2, 3}

b = {3, 4, 5}


print(a.symmetric_difference(b))  # Output: {1, 2, 4, 5}


11. Issubset() Method


The issubset() method in Python checks whether all elements of one set are contained within another set. It returns True if all elements are present, otherwise False. This method is useful for testing hierarchical or inclusion relationships between sets. Understanding issubset() helps in comparing and validating set data efficiently.


Syntax

set1.issubset(set2)


Example

a = {1, 2}

b = {1, 2, 3}


print(a.issubset(b))             # Output: True


12. Issuperset() Method


The issuperset() method in Python checks whether a set contains all elements of another set. It returns True if all elements of the other set are present, otherwise False. This method is the opposite of issubset() and is useful for verifying inclusion relationships. Understanding issuperset() helps in comparing sets and managing hierarchical data efficiently.


Syntax

set1.issuperset(set2)


Example

a = {1, 2, 3}

b = {1, 2}


print(a.issuperset(b))           # Output: True


13. Isdisjoint() Method


The isdisjoint() method in Python checks whether two sets have no elements in common. It returns True if their intersection is empty, otherwise False. This method is useful for determining whether sets are completely separate. Understanding isdisjoint() helps in efficiently analyzing relationships between sets.

Syntax

set1.isdisjoint(set2)


Example

a = {1, 2}

b = {3, 4}


print(a.isdisjoint(b))           # Output: True

Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.