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?
CodePudding user response:
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']
CodePudding user response:
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'])