Michael Gee
Michael Gee

Reputation: 541

Unable to append values into a list in a different function on Leetcode in Python

Hey guys what I'm trying to do is simply append lists into a list but it is unable to append the proper values for some reason. Here is my code:

class Solution(object):

def subsets(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    mylist = [] 
    nums.sort()
    self.helper(mylist, [], nums, 0)
    return mylist

def helper(self, mylist, templist, nums, start):

    mylist.append(templist)
    print(templist)
    for i in range(start, len(nums)):
        templist.append(nums[i])
        self.helper(mylist, templist, nums, i + 1)
        templist.pop()

The templist prints out the correct output like so:

[]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]

onto the console but the mylist just returns a list of empty lists according to leetcode like so:

[[],[],[],[],[],[],[],[]]

and I'm not sure why. If anyone can help that would be really nice!

Upvotes: 0

Views: 179

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

Because you are passing the same list into your recursive calls. It isn't temporary at all. Either pass a copy, or explicitly create a copy:

def helper(self, mylist, templist, nums, start):
    templist = templist.copy()
    mylist.append(templist)
    ....

Upvotes: 1

Related Questions