Python Set Add Item
Add Items to Sets in Python
In Python, sets are collections of unique items that are mutable, allowing you to add new items after the set has been created. This lesson will cover how to add single items, merge other sets, and incorporate various iterable objects into a set.
1. Add Items to a Set
Once a set is created, you cannot modify its existing items, but you can easily add new items using the add()
method.
Example: Add an Item to a Set Using the add() Method
python
1# Creating a set of colors
2colors_set = {"red", "blue", "green"}
3
4# Adding an item to the set
5colors_set.add("yellow")
6
7print(colors_set) # Output: {'blue', 'green', 'yellow', 'red'} (Order may vary)
2. Add Items from Another Set
To merge items from another set into the current set, you can use the update()
method. This method allows you to add all elements from one set to another.
Example: Add Elements from One Set to Another
python
1# Creating two sets
2shapes_set = {"circle", "square", "triangle"}
3more_shapes_set = {"rectangle", "oval", "hexagon"}
4
5# Updating the first set with items from the second set
6shapes_set.update(more_shapes_set)
7
8print(shapes_set) # Output: {'square', 'circle', 'rectangle', 'oval', 'triangle', 'hexagon'} (Order may vary)
3. Add Any Iterable Object
The update()
method does not have to be limited to sets; it can accept any iterable object, including lists, tuples, and dictionaries.
Example: Add Elements from a List to a Set
python
1# Creating a set of numbers
2numbers_set = {1, 2, 3}
3
4# Creating a list of additional numbers
5additional_numbers = [4, 5, 6]
6
7# Updating the set with elements from the list
8numbers_set.update(additional_numbers)
9
10print(numbers_set) # Output: {1, 2, 3, 4, 5, 6} (Order may vary)