There are a few ways to create sets, depending on which version of Python you use.
For 2.6 and earlier, which is available in later Pythons.
To make a set object, pass in a sequence or other iterable object to the built-in set function:
x = set('abcde') y = set('bdxyz') print( x ) # Pythons <= 2.6 display format # from w w w . ja va 2s. c o m
Sets support the common mathematical set operations with expression operators.
We can't perform the following operations on plain sequences like strings, lists, and tuples.
We must create sets from them by passing them to set in order to apply these tools:
x = set('abcde') y = set('bdxyz') print( x - y ) # Difference print( x | y ) # Union print( x & y ) # Intersection print( x ^ y ) # Symmetric difference (XOR) print( x > y, x < y ) # Super set, subset # from w ww . j av a 2s .c om
Set membership test
x = set('abcde') print( 'e' in x ) # Membership (sets) print( 'e' in 'Camelot', 22 in [11, 22, 33] ) # But works on other types too # ww w.j av a 2s . co m