-1

I have two sets set([1,2,3] and set([4,5,6]. I want to add them in order to get set 1,2,3,4,5,6.

I tried:

b = set([1,2,3]).add(set([4,5,6]))

but it gives me this error:

Traceback (most recent call last):

  File "<ipython-input-27-d2646d891a38>", line 1, in <module>
    b = set([1,2,3]).add(set([4,5,6]))

TypeError: unhashable type: 'set'

Question: How to correct my code?

vasili111
  • 6,032
  • 10
  • 50
  • 80

2 Answers2

2

You can take the union of sets with |

> set([1, 2, 4]) | set([5, 6, 7])
{1, 2, 4, 5, 6, 7}

Trying to use add(set([4,5,6])) is not working because it tries to add the entire set as a single element rather than the elements in the set — and since it's not hashable, it fails.

Mark
  • 90,562
  • 7
  • 108
  • 148
  • sorry for being pedantic but I think `a.union(b)` is cleaner. – Charlie Parker Aug 12 '21 at 15:36
  • I don't think that's pedantic @CharlieParker, just an opinion. `a.union(b)` is nice, so is `a | b`. Both loose a little luster when you solve the *actual* problem and write something like: `set([1, 2, 4]).union([5, 6, 7])` or set variables `a` and `b` first to give that nice, clean feel as @khuynh did below. – Mark Aug 12 '21 at 16:03
  • perhaps the reason I think it's pedantic is that `|` is usually used for Ors - for booleans. Yes it is isomorphic sort of to set union but the Or of a set doesn't really exist. What exists is the union of them. That's what I meant. – Charlie Parker Aug 15 '21 at 16:37
  • 'or' makes perfect sense here and the relationship between `or -> union` and `and -> intersection` is [common in the math literature](https://eng.libretexts.org/Bookshelves/Computer_Science/Programming_and_Computation_Fundamentals/Foundations_of_Computation_(Critchlow_and_Eck)/02%3A_Sets_Functions_and_Relations/2.02%3A_The_Boolean_Algebra_of_Sets). A union represents items in set A **or** set B. An intersection represents items in set A **and** set B. This is reflected in the choice of `|` and `&` for these operators. – Mark Aug 15 '21 at 16:46
1

You should use the union operation with the .union method or the | operator:

>>> a = set([1, 2, 3])
>>> b = set([4, 5, 3])
>>> c = a.union(b)
>>> print(c)
{1, 2, 3, 4, 5}
>>> d = a | b
>>> print(d)
{1, 2, 3, 4, 5}

See the complete list of operations for set.

kennyvh
  • 2,526
  • 1
  • 17
  • 26