Python Sets
Python sets
Python Sets
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.
Create a Set
thisset = {"apple", "banana", "cherry"}
print(thisset)
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
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.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can add new items.
Duplicates Not Allowed
Sets cannot have two items with the same value:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset) # {'banana', 'cherry', 'apple'}
Get the Length of a Set
To determine how many items a set has, use the len() function:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Access Items
You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
print("banana" in thisset)