Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set subtraction while casting lists and string

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading