0

i can't add set to python

you can add tuple to python set

a={1,2,3,4,5}
a.add((10,11,12))

when i try same with set

a={1,2,3,4,5}
a.add({10,11,12})
TypeError: unhashable type: 'set'
1
  • 1
    What result do you want? {1, 2, 3, 4, 5, 10, 11, 12}, or {1, 2, 3, 4, 5, {10, 11, 12}}? The latter is what this code tries to do.
    – Chris
    Commented Dec 9, 2022 at 16:08

2 Answers 2

0

You can add frozensets to a set, since they are hashable (because they are immutable).

a = {1,2,3,4,5}
a.add(frozenset([10,11,12]))
-1

I'd assume you are trying to get:

{1, 2, 3, 4, 5, 10, 11, 12}

You are appending a set which is unhashable. And when you add the tuple you will get:

{1, 2, 3, 4, 5, (10, 11, 12)}

You are trying you get the union:

a.union({10,11,12})

Or:

a | {10,11,12}
2
  • 2
    | you mean, don't you ?
    – keepAlive
    Commented Dec 9, 2022 at 16:10
  • Thanks for the heads up, was a quick post. I edited.
    – Jab
    Commented Dec 9, 2022 at 16:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.