Python sets
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.
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'}
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'}