Python Sets
Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Note: the set list is unordered, so the items will appear in a random order.
The set() Constructor
It is also possible to use the set() constructor to make a set. You can use the add() object method to add an item, and the remove() object method to remove an item from the set. The len() function returns the size of the set.
Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Run example »
Example
Using the add() method to add an item:
thisset = set(("apple", "banana", "cherry"))
thisset.add("damson")
print(thisset)
Run example »
Example
Using the remove() method to remove an item:
thisset = set(("apple", "banana", "cherry"))
thisset.remove("banana")
print(thisset)
Run example »
Example
Using the len() method to return the number of items:
thisset = set(("apple", "banana", "cherry"))
print(len(thisset))
Run example »