Question 23
What is the output of the following code?
Solution
Initially, sa = set('bananas') = {'b', 'a', 'n', 's') and sb = set('pyjamas') = {'p', 'y', 'j', 'a', 'm', 's'}.
Also, lc = list('pineapple') = ['p', 'i', 'n', 'e', 'a', 'p', 'p', 'l', 'e'].
The compound statement sa & sb produces a set of elements which only appear in both sa and sb, which results to {'a', 's'}.
Iterating through this new set, we add one of its elements into lc if it does not exist.
Only 's' does not exist, so it is appended to lc, making lc = ['p', 'i', 'n', 'e', 'a', 'p', 'p', 'l', 'e', 's'].
The compound statement sa ^ sb produces a set of elements that appear in either sa or sb, but not both (i.e., exclusive-or/XOR).
This results to {'b', 'n', 'p', 'y', 'j', 'm'}.
Iterating through this new set, if it exists in lc, remove it/the first instance from lc.
At this point, we remove the first instances of 'n' and 'p', leaving lc = ['i', 'e', 'a', 'p', 'p', 'l', 'e', 's'].
At the end, if we create a set out of lc, we remove all duplicate instances of existing elements inside lc, leaving set(lc) = {'i', 'e', 'a', 'p', 'l', 's'}.