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'])
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() .
Method 1: Using *set()It first removes the duplicates and returns a dictionary which has to be converted to list.
Try this:
>>> a = set(['a', 'b', 'c'])
>>> b = set(['c', 'd', 'e'])
>>> c = a.union(b)
Result:
set(['a','b','c', 'd', 'e'])
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With