Programming Essentials Python - Overview of Collections - Adding and Deleting elements - set

Let us see how we can add and delete elements to the set in Python.

  • We can add elements to set or update existing ones.

    • add

    • update

    • union

  • We can delete elements from the set using different functions.

    • pop

    • remove

    • discard

    • clear

s = {1, 2, 3, 3, 3, 4, 4}
s.add(5)
s
s.update?
s.update({4, 5, 6, 7}) # Updates the set on which update is invoked
s
s.union?
s = {1, 2, 3, 4, 5}

s.union({4, 5, 6, 7}) # Creates new set
s
s.pop?
s.pop()
s
s.remove?
s.remove(4)
s
s.remove(6) # 6 does not exist, throws KeyError
s = {1, 2, 3, 4, 5}
s.discard?
s.discard(4)
s
s.discard(6)
s
s.clear?
s.clear()
s

Hands-On Tasks

In order to solidify your understanding of adding and deleting elements in a set, you can try the following tasks:

  1. Create a new set and add elements using the add method.
  2. Update an existing set with new elements using the update method.
  3. Perform a union operation between two sets to create a new set.
  4. Delete elements from a set using the pop, remove, discard, and clear methods.

Conclusion

In this article, we discussed how to add and delete elements in a set in Python. Practice these operations to become proficient in handling sets efficiently. Feel free to engage with the community for further learning opportunities.

Watch the video tutorial here