Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add two sets?

Tags:

python

set

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'} 
like image 369
GThamizh Avatar asked Apr 15 '15 11:04

GThamizh


People also ask

Can we add 2 sets in Python?

Sets can be joined in Python in a number of different ways. For instance, update() adds all the elements of one set to the other. Similarly, union() combines all the elements of the two sets and returns them in a new set. Both union() and update() operations exclude duplicate elements.

Can a set be added to another set?

Once a set is created, you cannot change its items, but you can add new items.


2 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.

like image 96
TheBlackCat Avatar answered Sep 28 '22 20:09

TheBlackCat


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) 
like image 39
Haresh Shyara Avatar answered Sep 28 '22 21:09

Haresh Shyara