Python Forum
Understanding Functions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding Functions
#1
Hello all - trying to grasp the concept of functions and every time I think I have it, I realize I really don't. Wall Here are two examples I found online. I can SEE how they're different but the lightbulb hasn't gone off as to why the results are different. I tried visualizing the code in the pythontutor visualization tool but still not getting it. Can someone break this down for me like I'm a 2-year-old?

Example one:
# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist.append([1,2,3,4]);
   print "Values inside the function: ", mylist
   return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Output:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist = [1,2,3,4]; # This would assig new reference in mylist
   print "Values inside the function: ", mylist
   return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Output:
Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
Reply
#2
A function's parameter is a special case of a local variable in a function. It means that in your code, there are two mylist variables: one of them is a global variable defined at line 9, the other one is a local variable in function changeme() When the function is called the two variables point to the same value, the list [10, 20, 30]. The statement mylist.apppend() changes this list's content but both mylist variables still point to the same value. On the contrary the statement mylist = [1, 2, 3, 4] in example two changes the value pointed to by the local variable mylist (but not the value pointed to by the global variable mylist).
Reply
#3
(May-09-2018, 09:00 PM)Gribouillis Wrote: The statement mylist.apppend() changes this list's content but both mylist variables still point to the same value. On the contrary the statement mylist = [1, 2, 3, 4] in example two changes the value pointed to by the local variable mylist (but not the value pointed to by the global variable mylist).

I started to write you some questions but as I did this started to sink in. I understand it now. Thank you!!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020