Python - Set Set Introduction

Introduction

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:

Demo

x = set('abcde') 
y = set('bdxyz') 
print( x )       # Pythons <= 2.6 display format
# from  w  ww  . j  av a2 s .com

Result

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:

Demo

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
#   ww w.j a va 2 s .  co m

Result

Set membership test

Demo

x = set('abcde') 
print( 'e' in x )                                      # Membership (sets) 
print( 'e' in 'Camelot', 22 in [11, 22, 33] )          # But works on other types too
#  w ww  .  j  av  a2  s  .c  o  m

Result

Related Topics