Continuing with the Python theme -One of the guys on our Python discussion list wanted to know the difference between pass-by-value and pass-by-reference. Seeing how this same question has been asked a few time previously, I thought I would try and make a blog entry to give a simple explanation to demonstrate how it works. Some languages use pass-by-value, but Python on the other hand uses pass-by-reference. What is the difference you ask?Well pass by value is exactly what it sounds like - you pass the value (a copy of everything in the memory). This is bad when you're passing a 10,000 item list to a function - because you now have *two* 10,000 item lists. It's even worse when you have many times that amount of data. Python, OTOH passes by reference - instead of copying the list, a pointer to the list is passed, so when you see something like this:def do_something(a_list):
a_list[2] = 4mylist = [1,2,3,4]
do_something(mylist) now mylist is: [1,2,4,4].In call-by-value, the value of the arguments are copied into the function. There is no way to modify variables outside of the function since you don't have access to them, only to copies. C uses this, among many others: int a = 5
void func(int b) { b = 6; }
func(a);a == 5; /* evaluates to true, variable outside function scope remains unchanged */The value b, inside the function, contains a copy of a. So when it is
modified, the original a remains unchanged.Read more: Bringing Peace Through Programming
a_list[2] = 4mylist = [1,2,3,4]
do_something(mylist) now mylist is: [1,2,4,4].In call-by-value, the value of the arguments are copied into the function. There is no way to modify variables outside of the function since you don't have access to them, only to copies. C uses this, among many others: int a = 5
void func(int b) { b = 6; }
func(a);a == 5; /* evaluates to true, variable outside function scope remains unchanged */The value b, inside the function, contains a copy of a. So when it is
modified, the original a remains unchanged.Read more: Bringing Peace Through Programming
0 comments:
Post a Comment