So I'm trying to find all sub-lists of a list and here is what I have now. I'm new to Python and I don't understand why " Q3_ans=set(ans)" raises an error. I've tried to convert a list to set before and it works.
def f2(seq):
'''
This is the base case of the recursion from function all_sublists
'''
assert len(seq)==2
assert isinstance(x,list)
a,b=seq
return [[a],[b],[a,b]]
def all_sublists(x):
'''
This function will generate all of the sublists of a list, not including the empty one, using recursion
'''
assert isinstance(x,list)
ans=[]
for i in range(0,len(x)-1):
for j in range(1,len(x)):
temp=[x[i],x[j]]
temp=[f2(temp)]
ans.extend(temp)
Q3_ans=set(ans)
return Q3_ans
Here is the error when I run my code y=[1,2,3,4,5]
all_sublists(y)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-108-f8b1bb0a7001> in <module>
----> 1 all_sublists(y)
<ipython-input-106-84f4f752e98e> in all_sublists(x)
10 temp=[f2(temp)]
11 ans.extend(temp)
---> 12 Q3_ans=set(ans)
13 return Q3_ans
TypeError: unhashable type: 'list'
Here's the essence of the problem:
So, what does that mean?
set([iterable])
hashable
The keywords here are mutable
and immutable
So, you can't use a
list
asset
element. Atuple
would work:As you can figure out why, mutable types like lists can't be hashable, so can't be converted to a
set
. You can try returningtuple
instead; an immutable counterpart forlist
:then
You can read more about
tuple
type in the documentation.