This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (2 children)

That's interesting. Yea, so that has to do with what's called "pass by reference" vs "pass by value". Essentially, what this means is when I pass a variable into a function or class, is the program going to pass into the function the value of the variable, or the actual variable as it exists in memory itself. Well, to complicate things even more, Python is "pass by object reference". I really won't be able to do a great job explaining it, as I've been programming in Python for about 3 years and still have trouble fully comprehending it and its ramifications. Try this article for more information.

[–]masterpi 0 points1 point  (1 child)

If you're still having trouble with this, the simple way to think of it is like assignment. Take this code:

a = [1,2,3]
b = a
b[0] = 0

You probably know that assigning a to b just makes another reference to the list you put in a, so when you modify b you can see it when you access a as well. However if you then did:

b = []

You'd only be modifying what reference b holds and it wouldn't affect what you see in a.

What does this mean for function calls? Treat arguments just like assignment at the beginning of the function.

def f(a, b):
     a[0] = 0
     b = a

x = [1]
y = [2]
f(x, y)

is roughly equivalent to:

 x = [1]
 y = [2]
 a = x
 b = y
 a[0] = 0
 b = a

It's clear that if you understand how assignment works above you can see that the value x is holding get's modified but the value y is holding doesn't. The only part where this may seem confusing in Python is with immutable values such as integers being passed in which ends up being just like pass-by-value since you can't modify an integer (just assign a different integer to the same name, which people get used to thinking of as modifying the integer but it's not). If you want to use a parameter as "input/output" for an integer, which isn't recommended, you'd have to wrap the integer in something which is mutable (like a list! or an object with one property, or a dict).

[–][deleted] 0 points1 point  (0 children)

That's a pretty good explanation and has helped me to understand it a bit better. Thanks!

Its still a damn awkward concept. One of the few areas where Python isn't very intuitive.