Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python add two sets and delete duplicate elements

How to add two sets and delete duplicates

>>> a = set(['a', 'b', 'c'])
>>> b = set(['c', 'd', 'e'])
>>> c = a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'set' and 'set'
>>>

Expected output:
c = set(['a','b','c', 'd', 'e']) 
like image 309
abc Avatar asked Mar 12 '18 03:03

abc


People also ask

How do I remove duplicates from a list of sets?

Use set() This is a simple way to remove duplicates from a list. Sets are data structures that cannot contain any duplicate elements. When you convert a list into a set, all the duplicates will be removed. The set can then be converted back into a list with list() .

Does set automatically remove duplicates Python?

Method 1: Using *set()It first removes the duplicates and returns a dictionary which has to be converted to list.


3 Answers

Try this:

>>> a = set(['a', 'b', 'c'])
>>> b = set(['c', 'd', 'e'])
>>> c = a.union(b)

Result:

set(['a','b','c', 'd', 'e'])

like image 183
Delowar Hosain Avatar answered Oct 27 '22 21:10

Delowar Hosain


Use union method

You want to use the union method of a set:

c = a.union(b)

https://docs.python.org/2/library/stdtypes.html#frozenset.union https://docs.python.org/3/library/stdtypes.html?highlight=sets#frozenset.union

The union method is the same as the | operator, so the line of code above is equivalent to

c = a | b

Use in-place operator

If you have no need to retain a or b, it would be better to use the update method, which will add the new members in place. That is,

a.update(b)

will produce the union in the existing data structure a. This is also performed by the equivalent code

a |= b

Sidenote: use set literal

In the code you provide, it would be faster to use the set literal notation with {element, element, ...}:

a = {'a', 'b', 'c'}

because it will execute twice as fast and not generate the unused list object.

like image 45
Bennett Brown Avatar answered Oct 27 '22 22:10

Bennett Brown


You can get the union of both sets using the logical or operator |

a = set(['a', 'b', 'c'])
b = set(['c', 'd', 'e'])
c = a | b

print(c)

{'e', 'a', 'b', 'd', 'c'}

If you want the set ordered and as a list

c = sorted(list(c))
print(c)

['a', 'b', 'c', 'd', 'e']

like image 36
JahKnows Avatar answered Oct 27 '22 22:10

JahKnows