Set Methods

In Python, a set is an unordered collection of unique elements. Sets are mutable, meaning their contents can be modified after creation. Sets are useful when you need to store a collection of items without duplicates. In this lesson, you will learn about some common set methods that you can use to manipulate and interact with sets.

Creating Sets

You can create a set by enclosing elements inside curly braces {} or by using the set() constructor.

numbers = {1, 2, 3, 4}
nums = set([1, 2, 3])
fruits = {'apple', 'banana', 'cherry'}
empty_set = set()  # Creating an empty set

Note:

  • If you use curly braces {} without any elements, Python will interpret it as a dictionary. To create an empty set, use the set() constructor.

Adding Elements

You can add an element to a set using the add() method. It only adds the element if it's not already present.

Example:

fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')  # Adding a new element to the set
print(fruits)  # Output: {'apple', 'banana', 'cherry', 'orange'}

Explanation:

  • fruits.add('orange') adds 'orange' to the set.

Removing Elements

You can remove an element from a set using the remove() or discard() methods.

  • remove() raises a KeyError if the element is not found.
  • discard() does not raise an error if the element is not found.

Example:

fruits = {'apple', 'banana', 'cherry'}
fruits.remove('banana')  # Removes 'banana' from the set
print(fruits)  # Output: {'apple', 'cherry'}

fruits.discard('grape')  # Does nothing if 'grape' is not in the set

Explanation:

  • fruits.remove('banana') removes 'banana' from the set.
  • fruits.discard('grape') does not raise an error if 'grape' is not in the set.

You can also remove an arbitrary element using the pop() method. This removes and returns a random element from the set.

Example:

random_element = fruits.pop()  # Removes and returns a random element
print(random_element)
print(fruits)

Set Operations

Python sets support various set operations such as union, intersection, and difference.

1. union()

The union() method returns a new set that contains all elements from both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)  # Output: {1, 2, 3, 4, 5}

2. intersection()

The intersection() method returns a new set that contains only the elements present in both sets.

intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {3}

3. difference()

The difference() method returns a new set that contains all elements from the first set that are not present in the second set.

difference_set = set1.difference(set2)
print(difference_set)  # Output: {1, 2}

4. symmetric_difference()

The symmetric_difference() method returns a new set that contains elements that are in either of the sets, but not in both.

symmetric_diff_set = set1.symmetric_difference(set2)
print(symmetric_diff_set)  # Output: {1, 2, 4, 5}

5. issubset() & issuperset()

The issubset() method checks if all elements of the current set are in another set. The issuperset() method checks if the current set contains all elements of another set.

set1 = {1, 2, 3}
set2 = {1, 2}
print(set2.issubset(set1))  # Output: True
print(set1.issuperset(set2))  # Output: True

6. isdisjoint()

The isdisjoint() method checks if two sets have no elements in common. It returns True if the sets are disjoint, and False otherwise.

set1 = {1, 2, 3}
set2 = {4, 5, 6}
print(set1.isdisjoint(set2))  # Output: True

set3 = {3, 4}
print(set1.isdisjoint(set3))  # Output: False

Set Methods

Python provides several built-in methods to interact with sets. Below are some common ones:

1. add()

The add() method adds a single element to the set.

fruits = {'apple', 'banana'}
fruits.add('cherry')
print(fruits)  # Output: {'apple', 'banana', 'cherry'}

2. remove()

The remove() method removes a specified element from the set. It raises a KeyError if the element is not found.

fruits.remove('banana')
print(fruits)  # Output: {'apple', 'cherry'}

3. discard()

The discard() method removes a specified element from the set if it exists. It does nothing if the element is not found.

fruits.discard('orange')  # No error if 'orange' is not in the set
print(fruits)  # Output: {'apple', 'cherry'}

4. clear()

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

fruits.clear()
print(fruits)  # Output: set()

5. copy()

The copy() method returns a shallow copy of the set.

set1 = {1, 2, 3}
set2 = set1.copy()
print(set2)  # Output: {1, 2, 3}

Set Comprehension

You can create sets using a concise syntax called set comprehension.

Example:

squares = {x**2 for x in range(5)}
print(squares)  # Output: {0, 1, 4, 9, 16}

{x**2 for x in range(5)} creates a set with the squares of numbers from 0 to 4.

Task

Practice: Set Manipulation

Objective: Practice using set methods to manipulate and interact with sets.

  1. Create a Python File: Create a file named set_methods_practice.py.

  2. Add Elements: Add some elements to a set and print the set.

    Example:

    numbers = {1, 2, 3}
    numbers.add(4)
    print(numbers)
    
  3. Remove Elements: Remove an element from the set using remove() or discard().

    Example:

    numbers.remove(3)
    numbers.discard(5)  # Does nothing if 5 is not in the set
    print(numbers)
    
  4. Set Operations: Perform a union, intersection, and difference between two sets.

    Example:

    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    print(set1.union(set2))
    print(set1.intersection(set2))
    print(set1.difference(set2))
    
  5. Subset/Superset: Check if one set is a subset or superset of another set.

    Example:

    print(set1.issubset(set2))
    print(set1.issuperset(set2))
    
  6. Check Disjoint Sets: Check if two sets are disjoint.

    Example:

    print(set1.isdisjoint(set2))
    
  7. Clear the Set: Clear all elements from the set.

    Example:

    set1.clear()
    print(set1)
    

Copyright © 2025 Devship. All rights reserved.

Made by imParth