154
a = {'a', 'b', 'c'} 
b = {'d', 'e', 'f'}

How do I add the above two sets? I expect the result:

c = {'a', 'b', 'c', 'd', 'e', 'f'}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
GThamizh
  • 2,054
  • 3
  • 17
  • 19

5 Answers5

229

Compute the union of the sets using:

c = a | b

Sets are unordered sequences of unique values. a | b, or a.union(b), is the union of the two sets — i.e., a new set with all values found in either set. This is a class of operations called "set operations", which Python set types are equipped with.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
TheBlackCat
  • 9,791
  • 3
  • 24
  • 31
90

You can use .update() to combine set b into set a. Try this:

a = {'a', 'b', 'c'}
b = {'d', 'e', 'f'}
a.update(b)
print(a)

To create a new set, c you first need to .copy() the first set:

c = a.copy()
c.update(b)
print(c)
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Haresh Shyara
  • 1,826
  • 10
  • 13
9

Use the result of union() of a and b in c. Note: sorted() is used to print sorted output

a = {'a','b','c'} 
b = {'d','e','f'}
c = a.union(b)
print(sorted(c)) #this will print a sorted list

Or simply print unsorted union of a and b

print(c)  #this will print set c
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
1

If you wanted to subtract two sets, I tested this:

A={'A1','A2','A3'}
B={'B1','B2'}
C={'C1','C2'}
D={'D1','D2','D3'}

All_Staff=A|B|C|D
All_Staff=sorted(All_Staff.difference(B)) 
print("All of the stuff are:",All_Staff)

Result:

All of the stuff are: ['A1', 'A2', 'A3', 'C1', 'C2', 'D1', 'D2', 'D3']
Abz
  • 19
  • 4
1

Using unpack:

>>> c = {*a, *b}
>>> c
{'a', 'b', 'c', 'd', 'e', 'f'}
Denis
  • 940
  • 12
  • 16