32

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.

looks good

num= set([2,3,4])
emp= set()
print num|emp
>>>set([2, 3, 4])

confused

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
lcs
  • 432
  • 1
  • 4
  • 10

1 Answers1

44

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 4
    Or use [`set.update`](https://docs.python.org/2/library/stdtypes.html#set.update), rather than creating a new set each time – jonrsharpe Aug 07 '15 at 16:59