Skip to content

Question 11

Evaluate:

set('hello world') - set('word')
Hint

The way how sets work in Python is very, very similar to that in set theory. Given sets \(A = \{1, 2, 3\}\) and \(B = \{2, 4, 6\}\), \(A - B = \{1, 3\}\) and \(B - A = \{4, 6\}\).

Solution

With sets, the - operator is a difference operator. Meaning, given A - B, this results in a new set containing elements in A that are not in B.

  • set('hello world') produces {'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'}
  • set('word') produces {'w', 'o', 'r', 'd'}.

Note that in Python, sets do not have duplicate element values.

Between these two sets, the elements in common are 'w', 'o', 'r', and 'd'. Remove all occurences of these elements from set('hello world') to obtain your answer.

Answer
{'h', 'e', 'l', ' '}