Sets are an unordered, mutable, unique, iterable, collection of values. They are similar to the sets in mathematics. Logically you can picture them behaving much like a venn diagram would, with each set being one of the circles in the diagram. You can find more info here.
Set literals are written using curly braces and . The empty set is written as set()
to not conflict with the empty dict.
{2, 4, 6, 8}
set()
Only immutable values can be inside, thus lists and other dicts can't be inner values. If there are duplicate values, they are automatically collapsed into a single one.
{2, 2, 2} #> {2}
You can convert any iterable to a set using the set()
function.
>>> set([1, 2, 2, 4, 4])
{1, 2, 4}
>>> set('hello world')
{'h', 'e', 'l', 'o', 'w', 'r', 'd'}
Operation | Description |
---|---|
len(s) |
number of elements in set s (cardinality) |
x in s |
test x for membership in s |
x not in s |
test x for non-membership in s |
s.issubset(t) or s <= t |
test whether every element in s is in t |
s.issuperset(t) or s >= t |
test whether every element in t is in s |
s.union(t) or s | t |
new set with elements from both s and t |
s.intersection(t) or s & t |
new set with elements common to s and t |
s.difference(t) or s - t |
new set with elements in s but not in t |
s.symmetric_difference(t) or s ^ t |
new set with elements in either s or t but not both |
s.copy() |
new set with a shallow copy of s |
>>> 2 in {1, 2, 4}
True
>>> {1, 2, 3} | {3, 4}
{1, 2, 3, 4}
>>> {1, 2, 3} & {3, 4}
{3}
>>> {1, 2, 3} - {3, 4}
{1, 2}
Check out the standard library docs for sets for an overview of all the things you can do.
>>> even_nums = {x * 2 for x in range(4)}
{0, 2, 4}