Yisong Zhen
Yisong Zhen

Reputation: 37

python set manipulation :the simple script does not output right set after unioning or disjoining?

all_tags   = ['24', '02', '26', '03', '33', '32', '31', '30', '29', '68', '11']
ref_tag    = str('24')
union_tags = set(all_tags) | set(ref_tag)
left_tags  = set(all_tags) - set(ref_tag)
print(union_tags)
print(left_tags)

The above is the simple code which I expect elements in union_tags should be the same as those in all_tags. However, the result is set

(['24', '02', '26', '03', '33', '32', '31', '30', '29', '68', '2', '4', '11']) 

The union_tags instead contains two extra elements '2' and '4', which I think it is the result splitting the str '24'. Again, left_tags should exclude element '24'. However, the result still have the '24'.

Please let me know why. I use the python 2.7 as the interpreter.

Upvotes: 1

Views: 57

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

Set function accept an iterable with hashable items and convert it to a set object, and since strings are iterables when you pass the string 24 to your set function it converts your string to following set:

{'2', '4'}

And at last the unioin of this set with all_tags would contain items 2 and 4.

If you want to put the 24 in a set as one item you can use {} in order to create your expected set:

>>> ref_tag = {'24'}
set(['24'])

Upvotes: 3

Related Questions