Saturday, July 2, 2022

Python - Add and remove items from a set

# Sets are unordered, unchangeable, and unindexed
# Unchangeable means you cannot change the item in a set,
# but you CAN add or remove items from the set

# sets use curly brackets {}
myset = {"apple", "banana", "cherry"}

# No duplicates
myset = {"apple", "banana", "cherry", "apple"}
# {'apple', 'cherry', 'banana'}
print (myset)
# 3
print(len(myset))

# Loop through a set
for x in myset:
    print(x)

# Add item
myset.add("orange")
# {'orange', 'banana', 'cherry', 'apple'}
print(myset)

# Add items from another set to myset
tropical = {"pineapple", "mango", "papaya"}
myset.update(tropical)
# {'orange', 'apple', 'mango', 'papaya', 'banana', 'pineapple', 'cherry'}
print(myset)

myset.remove("orange")
# {'pineapple', 'cherry', 'mango', 'papaya', 'banana', 'apple'}
# (notice no 'orange')
print(myset)

# If you try to remove the item and it does not exist,
# Python will raise an error
# myset.remove("orange")

# However, the discard() method will NOT raise an error
myset.discard("pineapple")
print(myset)
myset.discard("pineapple")
print(myset)

# Pop removes the last item from the set
# Its return value is the item removed
x = myset.pop()
print(myset)

print("Notice that ", x , " no longer exists in the set: " , myset)


print("---")

# Clear removes all items from the set
myset.clear()
print(myset)
del myset
# This would raise an error because the set no longer exists
#print(myset)