DEV Community

Xue
Xue

Posted on

Until today I understand Python's variable scoping and name binding rules...

I'm writing Leetcode 113 (Path Sum II) today and find out the big difference between l = l[:-1] and l.pop() expecially if you need to use it in recursive function.

Long story short, I thought they're the same that if I do either inside a function where l is a passed in parameter. I was assuming the caller function's l will be changed whichever way. But apparently they're not.

A simply verification is:

def f(lst):
    lst = lst[:-1]
    print("Inside f:", lst)

x = [1, 2, 3]
f(x)
print("Outside f:", x)
Enter fullscreen mode Exit fullscreen mode

And the output is:

Inside f: [1, 2]
Outside f: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

For l = l[:-1], what really happens is l[:-1] creates a new list. = rebinds **the local variable l to the new list. The rebinds does **not affect the object list in the calling function. Even though the variable has the same name, it's just a new local reference, and the original list object is untouched.

Top comments (0)