Python Part5: Set and exception handling Try except finally
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:
See Also
Thanks for the info, looking forward to your next post.
ReplyDeleteWeb Design Company Philippines
You can also check this site for more info: digital marketing agency philippines
ReplyDeleteAre you looking for an all in one company that can handle Web Design Cardiff, logo design, ecommerce design, graphic design, brochure and flyer design? Look no further than W3 Web Designs Ltd. We have the experience to create a professional presence and brand for your business or project. Over the last 10 years, W3 Web Designs have been offering web design in Wales, we have earned the respect and trust of more than 700 different clients.
ReplyDelete