0

I’m trying to have all element in a nested list return in the form of set through this function, but errors occurred.

list = [[0,4], [2,4], 5, [[[7,2], 3], 4]]

def setof(list):
  bag = set()
  for item in list:
    try: bag.add(item)
    except TypeError: bag.add(setof(item))
  return bag

print(setof(list))

Errors:
try: bag.add(item)
TypeError: unhashable type: ‘list’
During handling of the above exception, another exception occurred:
print(setof(list))
except TypeError: bag.add(setof(item))
TypeError: unhashable the: ‘set’

Does anyone know why did this happen or how to fix it, or a better way of doing it? This is my first time here. Thanks!

Ci Leong
  • 92
  • 11

2 Answers2

0

bag.add(setof(item)) is trying to add a set as an element of bag, not combine the sets. Use

bag.update(setof(item))
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Your problem is coming from set.add(list). This is not something Python sets accept. So, you want to turn all the inner lists into sets. Try this:

def setof(lst):
    bag = set()
    for item in lst:
        try:
            bag.add(set(item))
        except TypeError:
            bag.add(set([item]))
    return bag
User 12692182
  • 927
  • 5
  • 16