Advertisement
makispaiktis

Set Methods

Jul 22nd, 2024
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. # 1. Add, remove, discard, pop
  2. fruits = {'apple', 'pear', 'banana', 'tomato', 'strawberry', 'apricot'}
  3. print(fruits)
  4. fruits.add('pineapple')
  5. fruits.add('mango')
  6. fruits.add('berry')
  7. print(fruits, '\n')
  8.  
  9. # Remove vs discard
  10. fruits.remove('pear')
  11. print(fruits)
  12. fruits.discard('strawberry')
  13. print(fruits, '\n')
  14.  
  15. # '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
  16. fruits.discard('orange')
  17. print(fruits)
  18. print(fruits.discard('orange'), '\n')
  19.  
  20. # Pop removes a RANDOM item
  21. fruits.pop()
  22. print(fruits, '\n')
  23.  
  24.  
  25.  
  26. # 2. Union, intersection, intersection_update
  27. fruits = {'apple', 'pear', 'banana', 'berry', 'melon', 'watermelon'}
  28. exotics = {'mango', 'pineapple', 'watermelon', 'passion fruit'}
  29. union = fruits.union(exotics)
  30. print(union)
  31. intersection = fruits.intersection(exotics)
  32. print(intersection)
  33. fruits.intersection_update(exotics)
  34. print(fruits)
  35.  
  36.  
  37.  
  38. # 3. Update, difference
  39. fruits = {"apple", "banana", "cherry"}
  40. companies = {"google", "microsoft", "apple"}
  41.  
  42. diff1 = fruits.difference(companies)
  43. print(diff1)
  44. diff2 = companies.difference(fruits)
  45. print(diff2, '\n')
  46.  
  47. symm_diff = companies.symmetric_difference(fruits)
  48. diff = diff1.union(diff2)
  49. print(symm_diff, diff == symm_diff, '\n')
  50.  
  51. fruits.update(companies)
  52. print(fruits)
  53.  
  54.  
  55.  
  56. # 4. Subset, superset
  57. 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'}
  58. vowels = {'a', 'e', 'i', 'o', 'u'}
  59. print(vowels.issubset(letters))
  60. print(letters.issuperset(vowels), '\n')
  61.  
  62. print(vowels.issuperset(vowels))
  63. print(letters.issuperset(vowels), '\n')
  64.  
  65. print(letters.issuperset({}))
  66. print(letters.issubset({}))
  67.  
  68.  
  69.  
  70. # 5. Disjoint
  71. # Returns True if no items in set x is present in set y:
  72.  
  73. x = {"apple", "banana", "cherry"}
  74. y = {"google", "microsoft", "facebook"}
  75. z = x.isdisjoint(y)
  76. print(z)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement