Sets

Creating Sets

  1. # create set
  2. fruits = {"apple", "banana", "cherry"}
  3. numbers = {1, 2, 3, 4, 5}
  4. empty = set()
  5. #ans: not {} - that's a dict!

Adding Elements

  1. # add single item
  2. fruits = {"apple", "banana"}
  3. fruits.add("cherry")
  4. #ans: {"apple", "banana", "cherry"}

Removing Elements

  1. # remove (raises error if not found)
  2. fruits = {"apple", "banana"}
  3. fruits.remove("apple")
  4. #ans: {"banana"}
  5. #ans: discard (no error if not found)
  6. fruits.discard("cherry")
  7. #ans: {"banana"}

Set Operations - Union

  1. # union (combines all)
  2. a = {1, 2, 3}
  3. b = {3, 4, 5}
  4. a | b
  5. #ans: {1, 2, 3, 4, 5}
  6. a.union(b)
  7. #ans: {1, 2, 3, 4, 5}

Set Operations - Intersection

  1. # intersection (common elements)
  2. a = {1, 2, 3}
  3. b = {2, 3, 4}
  4. a & b
  5. #ans: {2, 3}
  6. a.intersection(b)
  7. #ans: {2, 3}

Set Operations - Difference

  1. # difference (in a but not b)
  2. a = {1, 2, 3}
  3. b = {2, 3, 4}
  4. a - b
  5. #ans: {1}
  6. a.difference(b)
  7. #ans: {1}

Set Operations - Symmetric Difference

  1. # symmetric diff (in either but not both)
  2. a = {1, 2, 3}
  3. b = {2, 3, 4}
  4. a ^ b
  5. #ans: {1, 4}
  6. a.symmetric_difference(b)
  7. #ans: {1, 4}

Exercises - Part 1

  1. # duplicates in set?
  2. s = {1, 2, 2, 3}
  3. #ans: {1, 2, 3}

Exercises - Part 2

  1. # empty set?
  2. s = {}
  3. type(s)
  4. #ans: <class 'dict'>
  5. s = set()
  6. type(s)
  7. #ans: <class 'set'>

Exercises - Part 3

  1. # add existing element?
  2. s = {1, 2}
  3. s.add(2)
  4. #ans: {1, 2} (no change)

Exercises - Part 4

  1. # remove non-existent?
  2. s = {1, 2}
  3. s.remove(3)
  4. #ans: KeyError
  5. s.discard(3)
  6. #ans: no error

Exercises - Part 5

  1. # union result?
  2. a = {1, 2}
  3. b = {2, 3}
  4. a | b
  5. #ans: {1, 2, 3}

Exercises - Part 6

  1. # intersection empty?
  2. a = {1, 2}
  3. b = {3, 4}
  4. a & b
  5. #ans: set()

Exercises - Part 7

  1. # subset check?
  2. a = {1, 2}
  3. b = {1, 2, 3}
  4. a.issubset(b)
  5. #ans: True

Exercises - Part 8

  1. # set from list?
  2. lst = [1, 2, 2, 3]
  3. s = set(lst)
  4. #ans: {1, 2, 3}

Exercises - Part 9

  1. # set membership?
  2. s = {1, 2, 3}
  3. 2 in s
  4. #ans: True

Exercises - Part 10

  1. # pop from set?
  2. s = {1, 2, 3}
  3. s.pop()
  4. #ans: arbitrary element (unpredictable)

Google tag (gtag.js)