DEV Community

Cover image for Sets in Python
bluepaperbirds
bluepaperbirds

Posted on

Sets in Python

In Python, a set is a container whose objects must be unique. If you try to add something that's already in the set, it will not do anything (no error will be thrown).

Set example

Open the Python interactive shell to try it out. You can define a set by calling the set() method.

    >>> a = set([1,1,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4])
    >>> a
    {1, 2, 3, 4}
    >>> 

It uses curly braces { }, but don't be confused with a dictionary because it's a set. You can double check this with the type() function

    >>> type(a)
    <class 'set'>
    >>> 

To add elements to the set, use the .add(object) method.

    >>> a.add(4)
    >>> a.add(5)
    >>> a.add(6)
    >>> a
    {1, 2, 3, 4, 5, 6}
    >>> 

You can remove elements with the pop() method

    >>> a
    {2, 3, 4, 5, 6}
    >>> a.pop()
    2
    >>> a
    {3, 4, 5, 6}
    >>> 

To remove a specific item call the .remove() method

    >>> a.remove(5)
    >>> a    
    {3, 4, 6}
    >>> 

FrozenSet

A frozenset is different in mutability: it's frozen, cannot be changed, modified.

You can try adding or removing elements in the Python interactive shell:

>>> a = frozenset([1,1,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4])
>>> a
frozenset({1, 2, 3, 4})
>>> a.add(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>> 

Operations on sets

You can do a variety of operations on sets

>>> pets = { 'cat','parrot','dog' }
>>> zoo = { 'elephant','rhino','dog' }

Intersection of two sets

>>> pets & zoo
{'dog'}

Union of two sets

>>> pets | zoo
{'dog', 'parrot', 'elephant', 'rhino', 'cat'}

Symmetric difference of two sets

>>> pets ^ zoo
{'parrot', 'elephant', 'rhino', 'cat'}

Asymmetric difference of two sets

>>> pets - zoo
{'cat', 'parrot'}
>>> 

You can test if a set contains an object, by using the in keyword. This returns a boolean value (True/False).

>>> 'cat' in pets
True
>>> 'rhino' in pets
False
>>> 

The in keyword can also be applied to other sequences like tuples or lists.

The typical operations you'd expect like min(set), max(set) and len(set) can be applied too.

Top comments (1)

Collapse
 
waylonwalker profile image
Waylon Walker

Set operations in python are magical! They do seemingly complex operations in very simple readable code quickly.