Set
- Unordered collection of unique, immutable objects.
- Literals:
- Single comma separated items.
- >>> p = {1, 2, 3, 4}
- >>> p
- {1, 2, 3, 4}
- Empty { } makes a dict, so for empty set use the set() constructor.
- >>> e = set()
- >>> e
- set()
-
Set() constructor accepts:
- Iterable series of values.
- >>> s = set([1, 2, 3, 4])
- >>> s
- {1, 2, 3, 4}
- Duplicates are discarded.
- >>> t = [1, 2, 3, 1, 4]
- >>> set(t)
- {1, 2, 3, 4}
- Often used specifically to remove duplicates – not order preserving.
- Order is arbitrary.
- >>> for x in {1, 2, 4, 8, 32}
- print(x)
-
Use in and not in operators.
- >>> q = {2, 9, 6, 4}
- >>> 3 in q
- False
- >>> 3 not in q
- True
- Add(item) inserts a single element.
- >>> k = {2, 4}
- >>> k
- {2, 4}
- >>> k.add(8)
- >>> k
- {2, 4, 8}
-
Duplicates are silently ignored.
- >>> k.add(8)
- >>> k
- {1, 2, 8}
- For multiple elements use update(items) passing any iterable series.
- >>> k.update([9, 10])
- >>> k
- {1, 2, 8, 9, 10}
- Remove(item) requires that item is present, otherwise raises KeyError.
- >>> k.remove(9)
- >>> k
- {1, 2, 8, 10}
-
Discard(item) always succeeds.
- Copy set using S.copy() method.
- Use constructor. Set(s)
- Copies are shallows.
- S1.union(s2) method.
- s.intersection(t) method
- Intersection is commutative.
- s.difference(t) method.
- Difference is non-commutative.
- s.symmetric_difference(t) method
- Symmetric difference is commutative.
- s.issubset(t) method
- s.issuperset(t) method.
- s.isdisjoint(t)
Handle exceptions. Try … except … finally
- try:
- except:
- message = str(sys.exc_info()[1])
- x = -1
- finally: