Siddharth Kumar
Siddharth Kumar

Reputation: 698

Appending an empty list with list in recursive function

def permute(nums):
    result = []
    get_permute([], nums, result)
    return result

def get_permute(current, num, result):

    if not num:
        result.append(current+[])

    for i, v in enumerate(num):
        current.append(num[i])
        get_permute(current, num[:i] + num[i + 1:], result)
        current.pop()

if __name__ == "__main__":

    r = permute([1,2,3])

    for perm in r:
        print(perm)

What does current + [] do in result.append(current+[]) if I remove +[] it printing blank lists.

Upvotes: 1

Views: 883

Answers (2)

kalehmann
kalehmann

Reputation: 5011

What does the + [] do?

It generates a new list with the same contents as the old list.

>>> x = [1]
>>> id(x) == id(x + [])
False
>>> x == x + []
True

Why do I need this?

Whitout adding copies to your result, you would have the same list many times in your result and everytime you update that list, it affects your result.

>>> x = [1, 2]
>>> result = []
>>> result.append(x)
>>> x.append(3)
>>> result.append(x)
>>> result
[[1, 2, 3], [1, 2, 3]]

Some possible ways to make the could more readable would be

result.append(current[:])

or

result.append(list(current))

Why does it return blank lists if you remove the + []?

Because if you do not append copies to the result, there would be just one list in the result but multiple times. And you call .append(num[i]) on this list just as often as .pop(), which results in that list be empty.

Upvotes: 2

Patrick Haugh
Patrick Haugh

Reputation: 60974

It's making a copy of the list. When you remove it, you run into the List of lists changes reflected across sublists unexpectedly problem, because the outer list contains many references to the same list, instead of references to many different lists.

You should be able to replace it with current.copy() (using Python >= 3.3) or list(current) to avoid similar confusion among future readers. (There are a lot of ways to copy a list. Pick the one you like and stick with it.)

Upvotes: 4

Related Questions