python recursion pass by reference or by value?
<p>I am working the this problem on leetcode:</p>

<pre><code>Given a set of distinct integers, nums, return all possible subsets.
input =[1,2,3]
output =[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]
</code></pre>

<p>I have the c++ solution, which is accepted, and then i coded exactly the same python solution.</p>

<pre><code>class Solution(object):    
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        solutions = []
        self._get_subset(nums, 0, [], solutions)

        return solutions

    @staticmethod
    def _get_subset(nums, curr, path, solutions):
        if curr&gt;= len(nums):
            solutions.append(path)
            return

        path.append(nums[curr])
        Solution._get_subset(nums, curr+1, path, solutions)

        path.pop()
        Solution._get_subset(nums, curr+1, path, solutions)
</code></pre>

<p>The output is now:
    [[],[],[],[],[],[],[],[]]</p>

<p>It seems it is the Python pass by reference/ pass by value causing the problem, but i can't figure out how. The same c++ code works alright:</p>

<pre><code>class Solution {
public:
vector&lt;vector&lt;int&gt;&gt; subsets(vector&lt;int&gt;&amp; nums) {
    vector&lt;vector&lt;int&gt;&gt; solutions;
    vector&lt;int&gt; path;

    _get_path(nums, 0, path, solutions);
    return solutions;
}

void _get_path(vector&lt;int&gt;&amp; nums, 
               int curr,
               vector&lt;int&gt;&amp; path,
               vector&lt; vector&lt;int&gt; &gt; &amp;solutions)
{
    if(curr &gt;= nums.size()){
        solutions.push_back(path);
        return; 
    }
    path.push_back(nums[curr]);
    _get_path(nums, curr+1, path, solutions);

    path.pop_back();
    _get_path(nums, curr+1, path, solutions);
}
};
</code></pre>

<p>The problem is here:</p>

<pre><code>solutions.append(path)
</code></pre>

<p>in C++, <code>vector::push_back</code> makes a copy of <code>path</code> (internally). But in Python, everything is a reference. So you build up your <code>solutions</code> as a list of many references to the same <code>path</code>, which eventually gets reduced to nothing.</p>

<p>You want a copy:</p>

<pre><code>solutions.append(list(path))
</code></pre>

<p>or:</p>

<pre><code>solutions.append(path[:])
</code></pre>

python c++ recursion subset