Why doesn’t this:
def subsets(x):
if not x:
return [[]]
else:
return [x + y for x in [[], [x[0]]] for y in subsets(x[1:])]
print subsets(['a', 'b'])
produce the same output as this:
def subsets(x):
if not x:
return [[]]
else:
z = subsets(x[1:])
return [x + y for x in [[], [x[0]]] for y in z]
print subsets(['a', 'b'])
The problem is that you are using the name
xfor two different things. When you introducexas a variable inside a list comprehension it hides thexthat was defined in the function. As a result, the finalxin your list comprehension isn’t refering to thexthat you had hoped for.Renaming one of the
xto something else fixes the problem:I would also suggest that you try to find more descriptive names for your variables. This will reduce the likelihood of accidentally reusing a name.