Set subtraction while casting lists and string

Question:

I have two lists of strings. When I cast two lists into set() then subtraction works properly.

>>> A = ['One', 'Two', 'Three', 'Four']
>>> B = ['One']
>>> print(list(set(A) - set(B)))
['Three', 'Two', 'Four']

However when variable B is a string and I cast it into set() then, the subtraction is not working.

>>> A = ['One', 'Two', 'Three', 'Four']
>>> B = 'One'
>>> print(list(set(A) - set(B)))
['One', 'Two', 'Three', 'Four']

Is anyone able to explain me if its a bug or expected behavior?

Asked By: Daniel

||

Answers:

The set() function, when operating on a string, will generate a set of all characters:

print(set("ABC"))  # set(['A', 'C', 'B'])

If you want a set with a single string ABC in it, then you need to pass a collection containing that string to set():

print(set(["ABC"]))  # set(['ABC'])
Answered By: Tim Biegeleisen

This is expected. It considers the string as an iterable and thus creates a set of all letters.

B = 'One'
set(B)
# {'O', 'e', 'n'}

You can clearly see it if you have letters in A:

A = ['One', 'Two', 'Three', 'Four', 'O', 'o', 'n']
B = 'One'

print(list(set(A) - set(B)))

Output: ['o', 'Two', 'One', 'Four', 'Three']

Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.