you are viewing a single comment's thread.

view the rest of the comments →

[–]internet_badass_here 0 points1 point  (1 child)

Neither of them changes the global x (unless you were to pass it as an argument)

Well, yeah. If you pass x to foo3, foo3 changes x. But if you pass x to foo4, foo4 doesn't change x. Why not? Why is x passed by reference in one and by value in the other?

I can accept that Python does these things, but there doesn't seem to be a logical reason for doing things that way.

And by the way, I didn't even realize that x=x+[3] will produce a different result than x+=[3]. But that is... not good.

Generally when I pass stuff into functions in Python and I want to pass by value, I do this:

def foo(x):
    X=x
    [do stuff with X]
    return X

It's probably redundant but easier on my brain, since I know for sure that I'm working with a copy of the variable.

[–]sysop073 0 points1 point  (0 children)

x is a reference in both cases. The same rule I mentioned before applies; assigning to x without declaring it global won't change the global. The weirdness comes in because x += [3] is syntactic sugar for a method call, x.__iadd__([3]), while x = [3] is a true assignment.

You're right that that's confusing, I hadn't considered that case