Objectives:
Upon completion of this lesson, you should be able to:
Describe the characteristics of the builtin set
container in Python
Perform basic operations with set
s including creation, "querying", updates, and basic set operations
Get an idea in which situations set
s are and should be used
In Python, a set
is an efficient storage for "membership" checking
set
is like a dict
but only with keys and without values
Values are similar to "keys" in dict
and can be any Python data type BUT
they should be immutable
# Create an empty set
eng = set()
print eng
eng.add('one')
print eng
eng.add('two')
print eng
dict
but without values. As well as with dict
, the order of items in a set is unpredictableeng = {'one', 'two', 'three'}
print eng
You can create a set from an iterable (e.g. list):
eng = set(['one', 'two', 'three'])
print eng
Very similar to dict comprehensions:
{e for e in ['one', 'two', 'three'] if 'e' in e}
Very similar to lists and tuples:
6 in {4, 5, 6, 7}
True
eng.add('five')
print eng
eng.remove('five')
print eng
Why do we need sets if we could check for membership in lists and tuples?
set
is much faster¶def lookups(container):
for i in range(100, 200):
i in container
import random
l = range(1000)
random.shuffle(l)
t = tuple(l)
s = set(l)
%timeit lookups(l)
%timeit lookups(t)
%timeit lookups(s)
print dir(set)
{1, 2, 3, 'mom', 'dad'}.union({2, 3, 10})
{1, 2, 3, 'mom', 'dad'} | {2, 3, 10}
{1, 2, 3, 'mom', 'dad'}.intersection({2, 3, 10})
{1, 2, 3, 'mom', 'dad'} & {2, 3, 10}
{1, 2, 3, 'mom', 'dad'}.difference({2, 3, 10})
{1, 2, 3, 'mom', 'dad'} - {2, 3, 10}
More on sets could be found in the documentation: https://docs.python.org/2/library/stdtypes.html#set