Python From Beginner to Advanced

0% completed

Previous
Next
Python - Updating and Removing Elements From Set

Sets in Python are mutable, allowing elements to be added or removed dynamically. However, since sets do not maintain order, elements cannot be modified directly like lists. Instead, Python provides methods for adding and removing elements efficiently.

The most commonly used methods are:

  • add() – Adds a single element to the set.
  • update() – Adds multiple elements from another iterable.
  • discard() – Removes an element safely without causing an error.

Adding a Single Element

The add() method allows adding one element to a set.

Example 1: Using "add()" to Add an Element

Python3
Python3

. . . .

Explanation

  • num_set.add(4) adds 4 to the set.
  • If 4 already exists, the set remains unchanged.

Adding Multiple Elements

The update() method allows adding multiple elements from a list, tuple, or another set.

Example 2: Using "update()" to Add Multiple Elements

Python3
Python3

. . . .

Explanation

  • num_set.update([5, 6, 7]) adds multiple elements at once.
  • The argument must be an iterable (e.g., list, tuple, or another set).

Removing Elements from a Set

The discard() method removes an element without causing an error if the element is missing.

Example 3: Using "discard()" to Remove an Element

Python3
Python3

. . . .

Explanation

  • discard(20) removes 20 from the set.
  • discard(60) does nothing since 60 is not in the set, but no error is raised.

Python provides efficient methods to modify sets dynamically. These methods allow efficient modification of sets while preventing unnecessary errors.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next