How Do I Add Two Sets?

How Do I Add Two Sets?
a = {'a', 'b', 'c'} 
b = {'d', 'e', 'f'}

I want to add above two set values. I need output like

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

4 Answers

All you have to do to combine them is

c = a | b

Sets are unordered sequences of unique values. a | b or a.union(b) is the union of the two sets (a new set with all values found in either set). This is a class of operation called a "set operation", which Python sets provide convenient tools for.

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)

You can 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

    print(c)  #this will print set c
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.