0

I have this code written in Python:

def trick(l,i):
    if i==1:
        return l[0];
    else :
        return l[1]
def foo(x):
    x[0] = 'def'
    x[1] = 'abc'
    return x[1]
q = ['abc', 'def']
print(trick(q,1) == foo(q))
print(trick(q,1) == foo(q))
print(trick(q,0) == foo(q))

The output is this:

True
False
True

Why does the second print statement print "False" even though the second and the first print statements are the same. And when I visualized this code in Python tutor I got to know that the foo(x) function actually changes/swaps the elements in the original/global list 'q' even though 'x' should have local scope.

I can't understand this. Please help.

4
  • x is mutable. Nothing to do with the scope. you changed the items in x Commented Oct 23, 2017 at 19:43
  • 1
    You don't have separate global and local lists. There's only one list here. See nedbatchelder.com/text/names.html Commented Oct 23, 2017 at 19:43
  • @Jean-FrançoisFabre Yep, I changed the items in x, not in q. so in the second print statement, I am calling the same statement but the output is False. Why so? I thought q remained the same and only x changed. Commented Oct 23, 2017 at 19:44
  • @user2357112 Thank you so much. You can reply as an answer so I can mark it as the correct one. Commented Oct 23, 2017 at 19:49

1 Answer 1

1

While you do have separate global and local variables, you don't have separate global and local lists. Both q and x refer to the same list; the parameter passing mechanism doesn't make an implicit copy of the list. (Python almost never makes implicit copies.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.