I understand that any python set union
with empty set would result in itself. But some strange behave I detect when union
is inside of a for loop.
num= set([2,3,4])
emp= set()
print num|emp
>>>set([2, 3, 4])
s = set()
inp = ["dr101-mr99","mr99-out00","dr101-out00","scout1-scout2","scout3- scout1","scout1-scout4","scout4-sscout","sscout-super"]
for ele in inp:
r = set(ele.split("-"))
print r
s.union(r)
print s
>>>set(['mr99', 'dr101'])
set(['out00', 'mr99'])
set(['out00', 'dr101'])
set(['scout1', 'scout2'])
set(['scout1', 'scout3'])
set(['scout4', 'scout1'])
set(['scout4', 'sscout'])
set(['super', 'sscout'])
set([])
anyone could tell me why the last set s is empty? is the output supposed to be every unique element in the set?
s.union(r)
is a new set with elements from both s
and r
.reference You need to change
s.union(r)
to
s = s.union(r)
or, use set.update
.