0
0
Pythonprogramming~5 mins

Adding and removing set elements in Python

Choose your learning style9 modes available
Introduction

Sets let you store unique items. Adding and removing elements helps you change what is in the set easily.

You want to keep track of unique items like names or IDs.
You need to add new items without duplicates.
You want to remove items that are no longer needed.
You want to update a collection by adding or removing elements quickly.
Syntax
Python
my_set.add(element)
my_set.remove(element)
my_set.discard(element)
my_set.pop()

add() adds an element to the set.

remove() deletes an element but causes an error if the element is not found.

discard() deletes an element but does not cause an error if the element is missing.

pop() removes and returns an arbitrary element from the set.

Examples
Adds 'orange' to the set fruits.
Python
fruits = {'apple', 'banana'}
fruits.add('orange')
Removes 'banana' from the set fruits. Causes error if 'banana' is not in the set.
Python
fruits.remove('banana')
Tries to remove 'grape' but does nothing if 'grape' is not in the set.
Python
fruits.discard('grape')
Removes and returns an arbitrary element from fruits.
Python
item = fruits.pop()
Sample Program

This program shows how to add and remove elements from a set. It adds 'bird', removes 'cat', tries to discard 'fish' safely, and pops an element.

Python
my_set = {'cat', 'dog'}
print('Original set:', my_set)

my_set.add('bird')
print('After adding bird:', my_set)

my_set.remove('cat')
print('After removing cat:', my_set)

my_set.discard('fish')  # no error if not present
print('After discarding fish:', my_set)

popped = my_set.pop()
print('Popped element:', popped)
print('Set after pop:', my_set)
OutputSuccess
Important Notes

Sets do not keep order, so elements may appear in any order when printed.

Use discard() if you want to avoid errors when removing elements that might not be in the set.

pop() removes a random element because sets are unordered.

Summary

Use add() to add elements to a set.

Use remove() to delete elements but be careful if the element might not exist.

Use discard() to delete elements safely without errors.