Python Forum

Full Version: Powerset function alternative does not work
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I'm new to python (and to coding in general) and I need a powerset function. The one just below works fine, but I'm not familiar with the following notition:

newset = [subset + [x] for subset in result]
I try to replace it with the following code:
for subset in result:
newset = [subset + [x]] 
This however seems to generate an error. Can anyone please explain to me why this is the case? Thank you!

Full code:
def powerset(xs):
    result = [[]]
	for x in xs:	
		newset = [subset + [x] for subset in result]
		result.extend(newset)
	return result

print(powerset([0,1,2]))

def powerset2(xs):
	result = [[]]
	for x in xs:	
		for subset in result:
			newset = [subset + [x]]
			result.extend(newset)
	return result

#data = build_items(3)
print(powerset2([0,1,2]))
your second bit of code isn't indented properly