Set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable. However, the set itself is mutable (we can add or remove items). Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
Creating a Set in Python
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set()
. It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.
>>> # set of integers
>>> my_set = {1, 2, 3}
>>> # set of mixed datatypes
>>> my_set = {1.0, "Hello", (1, 2, 3)}
>>> # set donot have duplicates
>>> {1,2,3,4,3,2}
{1, 2, 3, 4}
>>> # set cannot have mutable items
>>> my_set = {1, 2, [3, 4]}
...
TypeError: unhashable type: 'list'
>>> # but we can make set from a list
>>> set([1,2,3,2])
{1, 2, 3}
Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use theset()
function without any argument.
>>> a = {}
>>> type(a)
<class 'dict'>
>>> a = set()
>>> type(a)
<class 'set'>
Changing a Set in Python
Sets are mutable. But since they are unordered, indexing have no meaning. We cannot access or change an element of set using indexing or slicing. Set does not support it. We can add single elements using the method add()
. Multiple elements can be added using update()
method. The update()
method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.
>>> my_set = {1,3}
>>> my_set[0]
...
TypeError: 'set' object does not support indexing
>>> my_set.add(2)
>>> my_set
{1, 2, 3}
>>> my_set.update([2,3,4])
>>> my_set
{1, 2, 3, 4}
>>> my_set.update([4,5], {1,6,8})
>>> my_set
{1, 2, 3, 4, 5, 6, 8}
Removing Elements from a Set
A particular item can be removed from set using methods like discard()
andremove()
. The only difference between the two is that, while usingdiscard()
if the item does not exist in the set, it remains unchanged. Butremove()
will raise an error in such condition. The following example will illustrate this.
>>> my_set = {1, 3, 4, 5, 6}
>>> my_set.discard(4)
>>> my_set
{1, 3, 5, 6}
>>> my_set.remove(6)
>>> my_set
{1, 3, 5}
>>> my_set.discard(2)
>>> my_set
{1, 3, 5}
>>> my_set.remove(2)
...
KeyError: 2