Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"} print(thisset)
Output
Note: Sets are unordered, so the items will appear in a random order.
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
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 thein
keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"} for x in thisset: print(x)
Output
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add()
method.
To add more than one item to a set use the update()
method.
Example
Add an item to a set, using the add()
method:
thisset = {"apple", "banana", "cherry"} thisset.add("orange") print(thisset)