hokkaidi
hokkaidi

Reputation: 910

Why can't I modify a list passed as an argument inside a function?

Here is the context. I have a tree structure defined like this:

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

and I am trying to recursively iterate over the tree with a function find_x. The function relies on a list to_do that is passed as an argument.

x = defaultdict(lambda:[])

def find_x (x, to_do):
    next_to_do = []

    for node, n in to_do:
        x[n].append(node.val)

        if node.left:
            next_to_do.append((node.left, n - 1))

        if node.right:
            next_to_do.append((node.right, n + 1))

    to_do = next_to_do

to_do = [(root, 0)]
while to_do:
    find_x(x, to_do)

When I run my function and I see that to_do is not updated. I understand that if I want to_do to be updated, I need to change find_x and replace the last line with return next_to_do and I need to change the inside of the while loop into to_do = find_x(x, to_do).

My question is this. Since my list to_do is a mutable object and since it is defined outside of the function find_x, the function find_x should be able to modify it. Why is it not not the case?

Thanks for your help!

Upvotes: 1

Views: 42

Answers (1)

kederrac
kederrac

Reputation: 17322

you are creating a new variable to_do inside of your function find_x, you may use:

to_do[:] = next_to_do

Upvotes: 2

Related Questions