GThamizh
GThamizh

Reputation: 2296

How do I add two sets?

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'}

Upvotes: 177

Views: 220380

Answers (5)

Denis
Denis

Reputation: 1258

Using unpack:

>>> c = {*a, *b}
>>> c
{'a', 'b', 'c', 'd', 'e', 'f'}

Upvotes: 3

Maaz Bin Mustaqeem
Maaz Bin Mustaqeem

Reputation: 159

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

Upvotes: 12

TheBlackCat
TheBlackCat

Reputation: 10308

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.

Upvotes: 265

Abz
Abz

Reputation: 29

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']

Upvotes: 2

Haresh Shyara
Haresh Shyara

Reputation: 1886

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)

Upvotes: 95

Related Questions