I'm trying to write a function in python that returns the powerset of a list inputted to it. In lines 5 and 6, I try to append an element to only the second half of the array but it apparently gets appended to all the elements of the array. Why does this happen and how can I fix it?
Code:
def powerset(array):
ans=[[]]
for elem in array:
ans.extend(ans.copy())
for j in range(int(len(ans)/2), len(ans)):
ans[j].append(elem)
return ans
Example input: [0, 1]
Output returned by above function: [[0, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1]]
Expected Output: [[], [0], [1], [0, 1]]