Python Set Methods Complete Guide

In Python, set methods provide a means to effectively and efficiently manipulate the contents of a set. These methods enable us to add, delete, and modify the items within sets. Sets in Python are characterized as an unordered and mutable data type, which permits the storage of a collection of distinct objects within a single variable.

Let's explore the different methods associated with sets in Python.

Method Description
add() This method is utilized to add a data element to the set.
clear() This method is utilized to remove all data elements from the set.
copy() This method is used to return a shallow copy of the set.
discard() This method is used to remove a data element if it is a member. It will not return any error if the specified element is not found in the set.
remove() This method is utilized to remove a data element from the given set; however, it raises a KeyError if the specified element is not found.
pop() This method is used to remove and return an arbitrary element.
update() This method is utilized to add elements from other sets or iterables.

1) add Method

The add function serves to introduce a new item into a set, guaranteeing that all elements remain unique. If the specified item is already a member of the set, there will be no alterations made to the existing set.

Syntax:

The syntax of the add method is shown below:

Example

set_name.add(item)

Python Set's add Method Example

We are about to examine a straightforward example that demonstrates the application of the set's add function in Python.

Example

Example

# python program to show the use of set add() method

# creating a set

set_of_fruits = {'apple', 'mango', 'banana', 'orange', 'guava'}

# printing the set

print("Set of Fruits:", set_of_fruits)

# using the add() method

set_of_fruits.add('grapes')

# printing the updated set

print("Updated Set of Fruits:", set_of_fruits)

Output:

Output

Set of Fruits: {'banana', 'orange', 'apple', 'guava', 'mango'}

Updated Set of Fruits: {'banana', 'orange', 'apple', 'guava', 'mango', 'grapes'}

Explanation:

In the preceding example, the add function has been utilized to insert a new item, 'grapes', into the specified set.

2) clear

The clear function is employed to eliminate every element from the specified set.

Syntax:

The syntax for the clear method is as follows:

Example

set_name.clear()

Python Set's clear Method Example

Let us now examine a practical example to grasp how the clear method functions within sets in Python.

Example

Example

# python program to show the use of set clear() method

# creating a set

game_set = {'football', 'cricket', 'volleyball', 'basketball', 'hockey'}

# printing the set

print("Given Set:", game_set)

# using the clear() method

game_set.clear()

# printing the updated set

print("Updated Set:", game_set)

Output:

Output

Given Set: {'basketball', 'hockey', 'football', 'cricket', 'volleyball'}

Updated Set: set()

Explanation:

In the preceding illustration, we employed the clear method to eliminate every element present in the specified set.

3) copy

In Python, the copy method is employed to create and return a shallow duplicate of the set.

Syntax:

Here is the syntax of the copy method:

Example

set_name.copy()

Python Set's copy Method Example

Let us examine an instance that illustrates the application of the copy method associated with sets in Python.

Example

Example

# python program to show the use of set copy() method

# creating a set

vegetable_set = {'potato', 'eggplant', 'tomato', 'cabbage', 'broccoli'}

# printing the set

print("Given Set:", vegetable_set)

# using the copy() method

dummy_set = vegetable_set.copy()

# printing the updated set

print("Dummy Set:", dummy_set)

Output:

Output

Given Set: {'potato', 'tomato', 'broccoli', 'eggplant', 'cabbage'}

Dummy Set: {'potato', 'tomato', 'broccoli', 'eggplant', 'cabbage'}

Explanation:

In this illustration, we have employed the copy method to generate a shallow replica of the specified set.

4) discard

The discard function is employed to eliminate elements from a set. Notably, this function does not generate an error if the specified element is absent from the set in question.

Syntax:

The syntax for the discard method is as follows:

Example

set_name.discard(item)

Python Set's discard Method Example

Let us now examine a straightforward example that demonstrates how to utilize the discard method of a set in Python.

Example

Example

# python program to show the use of set discard() method

# creating a set

beverage_set = {'milk', 'juice', 'soda', 'tea', 'coffee'}

# printing the set

print("Given Set:", beverage_set)

# using the discard() method

beverage_set.discard('soda')

# printing the updated set

print("Updated Set:", beverage_set)

Output:

Output

Given Set: {'juice', 'milk', 'coffee', 'tea', 'soda'}

Updated Set: {'juice', 'milk', 'coffee', 'tea'}

Explanation:

In this illustration, we have utilized the discard function to eliminate the designated element from the specified set.

5) remove

The remove function is employed to eliminate the indicated element from the set. If the element provided does not exist within the specified set, it will trigger an error.

Syntax:

Here is the syntax of the remove method:

Example

set_name.remove(item)

Python Set's remove Method Example

Now, let's examine an example that demonstrates the utilization of the remove method for sets in Python.

Example

Example

# python program to show the use of set remove() method

# creating a set

country_set = {'India', 'Brazil', 'Japan', 'China', 'USA'}

# printing the set

print("Given Set:", country_set)

# using the remove() method

country_set.remove('China')

# printing the updated set

print("Updated Set:", country_set)

Output:

Output

Given Set: {'Brazil', 'China', 'India', 'Japan', 'USA'}

Updated Set: {'Brazil', 'India', 'Japan', 'USA'}

Explanation:

In the preceding illustration, we utilized the remove function to eliminate the designated element from the specified set.

6) pop

The pop method in Python sets enables the removal of an arbitrary element from the set. Upon execution, this method returns the element that has been removed.

Syntax:

The syntax of the pop method is shown below:

Example

set_name.pop()

Python Set's pop Method Example

Next, we will examine a straightforward example that demonstrates how to utilize the pop method of a set in Python.

Example

Example

# python program to show the use of set pop() method

# creating a set

state_set = {'New York', 'Delhi', 'Tokyo', 'Penang', 'Ontario'}

# printing the set

print("Given Set:", state_set)

# using the pop() method

popped_item = state_set.pop()

# printing the updated set

print("Updated Set:", state_set)

print("Popped Element:", popped_item)

Output:

Output

Given Set: {'Penang', 'Ontario', 'Tokyo', 'New York', 'Delhi'}

Updated Set: {'Ontario', 'Tokyo', 'New York', 'Delhi'}

Popped Element: Penang

Explanation:

In the preceding illustration, the pop function has been utilized to eliminate and retrieve an arbitrary element from the specified set.

7) update

The update method in Python sets serves the purpose of incorporating elements from another set, list, tuple, or any iterable into an existing set. Given that sets consist of distinct elements, the update method will exclusively introduce unique elements from the provided iterable to the designated set.

Syntax:

The syntax for the update function is as follows:

Example

set_name.update(*others)

Python Set's update Method Example

Next, we will examine a straightforward example that demonstrates the application of the update method for sets in Python.

Example

Example

# python program to show the use of set update() method

# given sets

num_set_1 = {4, 7, 8, 11, 19}

num_set_2 = {2, 5, 7, 8, 10}

print("Set 1:", num_set_1)

print("Set 2:", num_set_2)

# using the update() method

num_set_1.update(num_set_2)

# printing the updated set

print("Updated Set:", num_set_1)

Output:

Output

Set 1: {19, 4, 7, 8, 11}

Set 2: {2, 5, 7, 8, 10}

Updated Set: {2, 4, 5, 7, 8, 10, 11, 19}

Explanation:

In this instance, we utilized the update function to incorporate the elements from the second set into the first one. Consequently, only distinct elements are included in the set.

Set Operation Methods in Python

To carry out set operations such as union, intersection, difference, and symmetric difference, Python provides an array of set methods that can be utilized.

The following techniques can be utilized to execute set operations:

Method Description
union() This method is utilized to return a set with elements from the set and all others.
intersection() This method is utilized to return a set with common elements.
difference() This method returns elements only in the set but not in others.
symmetric_difference() This method returns elements in either set but not both.
intersection_update() This method allows us to update the set with intersection.
difference_update() This method is used to update the set with differences.
symmetricdifferenceupdate() This method updates the set with symmetric differences.
issubset() This method allows us to check if the set is a subset.
issuperset() This method is used to check if the set is a superset.
isdisjoint() This method checks if sets have no elements in common.

Let us see an example showing the use of some commonly used methods to perform set operations in Python.

Example

Example

# simple python program to see the use of set operation methods

# given sets

set_A = {3, 6, 7, 9, 12}

set_B = {1, 2, 6, 7, 10}

print("Set A:", set_A)

print("Set B:", set_B)

print()

# union

union_set = set_A.union(set_B)

print("Union:", union_set)

# intersection

inters_set = set_A.intersection(set_B)

print("Intersection:", inters_set)

# difference

diff_set = set_A.difference(set_B)

print("Difference (set_A - set_B):", diff_set)

# symmetric difference

sym_diff_set = set_A.symmetric_difference(set_B)

print("Symmetric Difference:", sym_diff_set)

Output:

Output

Set A: {3, 6, 7, 9, 12}

Set B: {1, 2, 6, 7, 10}

Union: {1, 2, 3, 6, 7, 9, 10, 12}

Intersection: {6, 7}

Difference (set_A - set_B): {9, 3, 12}

Symmetric Difference: {1, 2, 3, 9, 10, 12}

Explanation:

In this instance, we have executed various set operations including union, intersection, difference, and symmetric difference by utilizing the set methods provided by Python.

Python Set Methods MCQs

  1. What will be the result produced by executing the following code?
  2. Example
    
    set_A = {4, 7, 9}
    
    set_A.add(5)
    
    print(set_A)
    
  • {4, 7, 9}
  • {4, 7, 9, 5}
  • [4, 7, 9, 5]
  1. Which method removes all elements from a set?
  • clear
  • remove
  • delete
  • discard

Correct Response: a) clear

  1. What occurs if you attempt to incorporate a list into a set utilizing the add method?
  2. Example
    
    set_A = set()
    
    set_A.add([3, 5])
    
  • Nothing happens
  • Raises TypeError
  • Adds elements individually
  1. Which of the following methods returns 'True' if sets have no elements in common?
  • issubset
  • issuperset
  • difference
  • isdisjoint

Accurate Response: d) isdisjoint

  1. What will the following code produce as output?
  2. Example
    
    a = {4, 6}
    
    b = {6, 8}
    
    print(a.symmetric_difference(b))
    
  • {4, 8}
  • {4, 6, 8}

Input Required

This code uses input(). Please provide values below: