Python - Data Type Set

Introduction

Sets are unordered collections of unique and immutable objects.

You create sets by calling the built-in set function or using new set literals and expressions.

Python set support the mathematical set operations:

Demo

X = set('test')                 # Make a set out of a sequence in 2.X and 3.X 
Y = {'h', 'a', 'm'}             # Make a set with set literals in 3.X and 2.7 
print( X, Y )                            # A tuple of two sets without parentheses 
print( X & Y )                           # Intersection 
print( X | Y )                           # Union 
print( X - Y )                           # Difference 
print( X > Y )                           # Super set 
print( {n ** 2 for n in [1, 2, 3, 4]} )  # Set comprehensions in 3.X and 2.7
# from   w  w  w .j av  a 2s. c o  m

Result

Set is useful for filtering out duplicates, isolating differences, and performing order-neutral equality tests without sorting-in lists, strings, and all other iterable objects:

Demo

print( list(set([1, 2, 1, 3, 1])) )      # Filtering out duplicates (possibly reordered) 
print( set('test') - set('best') )        # Finding differences in collections 
print( set('test') == set('asmp') )      # Order-neutral equality tests (== is False)
#   w w w  .  j a va2  s.  c o m

Result

Sets support in membership tests, though all other collection types in Python do too:

Demo

print( 'p' in set('test'), 'p' in 'test', 'ham' in ['eggs', 'test', 'ham'] )

Result