Python sets

  1. Sometimes we want to deal with sets of things. We can make a set from a list. Note how Python writes a set with braces { }.

    >>> beatles = 'john paul george ringo'.split()
    >>> beatles
    ['john', 'paul', 'george', 'ringo']
    >>> set(beatles)
    {'ringo', 'paul', 'john', 'george'}
    >>> ledzeps = 'jimmy robert john john'.split()
    >>> ledzeps
    ['jimmy', 'robert', 'john', 'john']
    >>> set(ledzeps)
    {'john', 'robert', 'jimmy'}
    

    Note how the order in which the elements are presented may not be the order of input. A set has no inherent order. Python chooses its own order.

  2. We can also make sets from strings. We get a set of characters.

    >>> aa = set('anybody')
    >>> bb = set('banana')
    >>> aa
    {'a', 'b', 'd', 'n', 'o', 'y'}
    >>> bb
    {'a', 'b', 'n'}
    
  3. And we can carry out standard set operations such as difference, intersection, union and symmetric difference:

    >>> aa - bb
    {'y', 'd', 'o'}
    >>> aa & bb
    {'a', 'b', 'n'}
    >>> aa | bb
    {'a', 'b', 'd', 'y', 'o', 'n'}
    >>> aa ^ bb
    {'y', 'd', 'o'}
    

Author: Breanndán Ó Nualláin <o@uva.nl>

Date: 2025-02-10 Mon 14:45