- Expression is added to a set
- Transform iterable to set - with modification
- A set comprehension is useful for turning any sequence into a set. Items can be modified or skipped as the set is built.
- If you don't need to modify the items, it's probably easier to just pass the sequence to the set() constructor.
- Sets can be used to remove duplicate values from a list.
>>> import re
>>> with open("mary.txt") as mary_in:
... s = {w.lower() for ln in mary_in for w in re.split(r'\W+', ln) if w}
...
>>> s
{'about', 'go', 'why', 'so', 'it', 'lamb', 'made', 'know', 'mary', 'as', 'to', 'children', 'that', 'patiently', 'her', 'one', 'fleece', 'was', 'little', 'went', 'everywhere', 'reply', 'lingered', 'near', 'and', 'white', 'day', 'had', 'eager', 'whose', 'does', 'the', 'he', 'snow', 'waited', 'did', 'against', 'teacher', 'but', 'see', 'till', 'cried', 'loves', 'sure', 'rules', 'school', 'out', 'laugh', 'love', 'which', 'play', 'you', 'a', 'still', 'at', 'appear', 'turned', 'followed'}
s.add('Sandy')
s.update('Sandy','beach') #Duplicate adds/updates will not be added, as a set is a unique list.
s.remove('Sandy)
# or
s.discard('Sandy') #discard will not show an error if Sandy doesn't exist in the set like remove will.