Initializing sets (set, {,,,})
set([1, 2, "a"])
{1, 2, 'a'}
{1, 2, "a"}
{1, 2, 'a'}
set() # empty set
set()
{} # empty dictionary, not the empty set!
{}
Adding and deleting elements (.add, .remove, .discard, .pop, .clear)
s1 = {1, 2, 3, "a", "b"}
s2 = {2, 4, 6, "a", "c"}
s3 = {3, 33}
s1.add("d")
s1, s2, s3
({1, 2, 3, 'a', 'b', 'd'}, {2, 4, 6, 'a', 'c'}, {3, 33})
s1.remove("c")
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-72ce1ccfa9ab> in <module> ----> 1 s1.remove("c") KeyError: 'c'
s1.discard("c") # no error message if the element is not in the set
s1
{1, 2, 3, 'a', 'b', 'd'}
s1.pop() # delets one element and returns it
1
s1
{2, 3, 'a', 'b', 'd'}
Operations: union, update, intersection, isdisjoint, difference, symmetric_difference, |, &, -, ^,
s1.union(s2) # returns the union, but does not change s1
{2, 3, 4, 6, 'a', 'b', 'c', 'd'}
s1
{2, 3, 'a', 'b', 'd'}
s1.update(s3) # update s1 with the union; s3 can be list, tuple...
s1
{2, 3, 33, 'a', 'b', 'd'}
s1 | s2
{2, 3, 33, 4, 6, 'a', 'b', 'c', 'd'}
s1 & s2
{2, 'a'}
s1 - s2
{3, 33, 'b', 'd'}
s1 ^ s2
{3, 33, 4, 6, 'b', 'c', 'd'}