Python Tutorial

Add/Access Elements to Python Set

How to Add Elements to a Set in Python?

Once a set has been made, you can't change the parts, but you can add new ones. For adding a single element to a set in Python, use the add() function.


Add an item to a set, using the add() method.

thisset = {"cranberry", "blueberry", "apricot"}




{'blueberry', 'cranberry', 'orange', 'apricot'}

How to Access Elements in a Python Set?

You can’t access a set in Python with reference to an index. It is because the sets are unordered and there is no index for items. However, you can use a For loop to loop through the items in a set. Alternatively, you can use the keyword with ask if and find whether the required value is available in the set. 


# Create a set

set1 = set(["Ws", "Cube", "Tech"])

print("\nInitial set")


# Access element from set using

# for loop

print("\nElements of set: ")

for i in set1:

    print(i, end=" ")

# Check the element

# using in keyword

print("Ws" in set1)


Initial set: 
{Ws, Cube}
Elements of set: 
Ws Cube 
Did you find this article helpful?