Python Set Access Element
Access Set Items in Python
In Python, sets are unique collections that do not support indexing or key access. Instead, you can loop through the set items or check for the presence of a specific value using the in
keyword. This lesson will cover how to access items in a set and how to modify the set by adding new items.
1. Accessing Items in a Set
You cannot access items in a set using an index or a key because sets are unordered collections. However, there are effective methods to interact with set items.
1.1 Checking for Presence of an Item
You can use the in
keyword to check if a specific value is present in a set.
Example: Check if "apple" is Present in the Set
python
1# Creating a set
2fruits_set = {"apple", "banana", "cherry"}
3
4# Checking for the presence of "apple"
5print("apple" in fruits_set) # Output: True
Example: Check if "apple" is NOT Present in the Set
python
1# Creating a set
2fruits_set = {"apple", "banana", "cherry"}
3
4# Checking if "apple" is NOT present
5print("apple" not in fruits_set) # Output: False
2. Modifying Set Items
While you cannot change existing items in a set directly, you can add new items to the set.
Adding New Items
You can use the add()
method to insert a single item into the set.
Example: Add a New Item to the Set
python
1# Creating a set
2fruits_set = {"apple", "banana", "cherry"}
3
4# Adding a new item
5fruits_set.add("orange")
6
7print(fruits_set) # Output: {'banana', 'cherry', 'orange', 'apple'} (Order may vary)
Adding Multiple Items
If you want to add multiple items at once, you can use the update()
method.
Example: Add Multiple Items to the Set
python
1# Creating a set
2fruits_set = {"apple", "banana", "cherry"}
3
4# Adding multiple items
5fruits_set.update(["kiwi", "mango"])
6
7print(fruits_set) # Output: {'banana', 'cherry', 'mango', 'apple', 'kiwi'} (Order may vary)