Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable*, and unindexed.
Sets are written with curly brackets.
Example-
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Sets cannot have two items with the same value.
Example-
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
To determine how many items a set has, use the len() function.
Example-
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Set items can be of any data type:
Example-
String, int and boolean data types:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
From Python's perspective, sets are defined as objects with the data type 'set':
Example-
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
To add one item to a set use the add() method.
Example-
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
To add items from another set into the current set, use the update() method.
Example-
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
To remove an item in a set, use the remove(), or the discard() method.
Example-
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)