Set add() in python
Our aim in this article is to meet your learning objectives by examining Python sets add with examples.
set.add( elem )
- elem: To which a set should be added.
Add Any Iterable
You can add items of a list to a set:
Set Add – New Items
In Python sets add, once a set is created, you cannot change its items, but you can add new ones.
Use the add() method to add one item to a set.
Using the add() method, add an item to a set:
Add integer items to a set using the add() method:
Sets Add – Update Items
Use the update() method to add items from another set to the current set.
Adding elements from country_set1 to country_set:
Update integer to odd_set from even_set:
Set add() method Uses
Here are some common use cases for the
- You can use the
add()method to add individual elements to a set. If the element is already present in the set, it will be ignored since sets only contain unique elements.
- When you don’t know the initial elements of a set and need to build it dynamically, you can start with an empty set and use the
add()method to add elements one by one as you encounter them or as they become available.
- By starting with an empty set and using the
add()method in a loop, you can construct a set from an iterable object like a list, tuple, or string. This allows you to extract unique elements from the iterable and store them in the set.
- If you have an existing set and want to add new elements to it, you can use the
add()method to append individual elements. This is particularly useful when you have multiple sources of elements and want to combine them into a single set.
add()method can also be used to check whether an element is already present in the set. If the element is successfully added, it indicates that it was not already present. This can be useful for detecting and processing unique values.