In the following code:
all_subsets = []
subsets = [[], [2]]
left_most = 1
for subset in subsets:
print subset
all_subsets.append(subset)
all_subsets.append(subset.append(left_most))
print all_subsets
I suppose the return should be [[], [1], [2], [2, 1]], but I actually got the return of [[1], None, [2, 1], None]. i.e., [] has been converted to None.
I suppose it’s the problem of modifying subset in the loop twice, which pointing to the same physical address. However, I can’t fix the problem even if I make a local copy before modify the list, such as the following:
all_subsets = []
subsets = [[], [2]]
left_most = 1
for subset in subsets:
print subset
subset_orig = list(subset)
subset_plus = list(subset).append(left_most)
all_subsets.append(subset_orig)
all_subsets.append(subset_plus)
print all_subsets
Any idea? Thanks!
The problem is that
append()modifies the list in-place, and returnsNone.Here is one way to fix the code:
This produces
[[], [1], [2], [2, 1]]as you expect.