Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 1. Add, remove, discard, pop
- fruits = {'apple', 'pear', 'banana', 'tomato', 'strawberry', 'apricot'}
- print(fruits)
- fruits.add('pineapple')
- fruits.add('mango')
- fruits.add('berry')
- print(fruits, '\n')
- # Remove vs discard
- fruits.remove('pear')
- print(fruits)
- fruits.discard('strawberry')
- print(fruits, '\n')
- # 'Remove' is the exact same method as 'discard', but 'remove' method will RAISE AN ERROR if the specified item DOES NOT EXIST, while 'discard' won't do so
- fruits.discard('orange')
- print(fruits)
- print(fruits.discard('orange'), '\n')
- # Pop removes a RANDOM item
- fruits.pop()
- print(fruits, '\n')
- # 2. Union, intersection, intersection_update
- fruits = {'apple', 'pear', 'banana', 'berry', 'melon', 'watermelon'}
- exotics = {'mango', 'pineapple', 'watermelon', 'passion fruit'}
- union = fruits.union(exotics)
- print(union)
- intersection = fruits.intersection(exotics)
- print(intersection)
- fruits.intersection_update(exotics)
- print(fruits)
- # 3. Update, difference
- fruits = {"apple", "banana", "cherry"}
- companies = {"google", "microsoft", "apple"}
- diff1 = fruits.difference(companies)
- print(diff1)
- diff2 = companies.difference(fruits)
- print(diff2, '\n')
- symm_diff = companies.symmetric_difference(fruits)
- diff = diff1.union(diff2)
- print(symm_diff, diff == symm_diff, '\n')
- fruits.update(companies)
- print(fruits)
- # 4. Subset, superset
- letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}
- vowels = {'a', 'e', 'i', 'o', 'u'}
- print(vowels.issubset(letters))
- print(letters.issuperset(vowels), '\n')
- print(vowels.issuperset(vowels))
- print(letters.issuperset(vowels), '\n')
- print(letters.issuperset({}))
- print(letters.issubset({}))
- # 5. Disjoint
- # Returns True if no items in set x is present in set y:
- x = {"apple", "banana", "cherry"}
- y = {"google", "microsoft", "facebook"}
- z = x.isdisjoint(y)
- print(z)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement