473,750 Members | 2,279 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing arguments to function - (The fundamentals are confusing me)

Hey guys, would someone mind giving me a quick rundown of how
references work in Python when passing arguments into functions? The
code below should highlight my specific confusion:

<code>

bool1=True
lst1=[1,2,3]

def func1(arg1): arg1.append(4)

def func2(arg1): arg1=False
func1(lst1)
lst1 [1,2,3,4]
func2(bool1 )
bool1

True

</code>

Why does my list variable get changed for the rest of the program, but
my boolean variable doesn't. What am I not understanding?

--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
Aug 9 '05 #1
20 1994
Gregory Piñero wrote:
Hey guys, would someone mind giving me a quick rundown of how
references work in Python when passing arguments into functions? The
code below should highlight my specific confusion:
All arguments are passed by reference, but in Python equality rebinds
the name.

<code>

bool1=True
lst1=[1,2,3]

def func1(arg1): arg1.append(4)
In C++, pretending it had dynamic typing, this would be equivalent to:
void func1( * arg1){
arg1->append(4);
}

def func2(arg1): arg1=False void func2 ( * arg2) {
arg2 = &(False);
Why does my list variable get changed for the rest of the program, but
my boolean variable doesn't. What am I not understanding?


In Python, "x = y" has a very definite meaning of "y is assigned to the
name of x." This change does not affect whatever was in x to start
with, and it certainly would not affect anything else which holds a
reference to the object formerly known as x.

In contrast, calling a function which mutates the object (like .append
on lists, or assignment by lst[index]=something) actually changes the
object itself, which is of course reflected by all other names that hold
a reference to the object.
Aug 9 '05 #2
Christopher Subich wrote:
Gregory Piñero wrote:
Hey guys, would someone mind giving me a quick rundown of how
references work in Python when passing arguments into functions? The
code below should highlight my specific confusion:
This URL is always tossed out:

http://starship.python.net/crew/mwh/...jectthink.html
All arguments are passed by reference, but in Python equality rebinds
the name.
Bingo
Why does my list variable get changed for the rest of the program, but
my boolean variable doesn't. What am I not understanding?


Booleans are immutable, lists are mutable. You change (mutate) the same
list, but you are referencing a different (immutable) Bool
In Python, "x = y" has a very definite meaning of "y is assigned to the
name of x."


Change it to "the object referenced by y is assigned to the name of x",
and you're closer to the truth.
Aug 9 '05 #3
> in Python equality rebinds the name

Assignment (=) rebinds the name. Equality (==) is something else
entirely.

Aug 9 '05 #4
On Tue, 9 Aug 2005 10:53:15 -0400, Gregory Piñero <gr********@gma il.com>
declaimed the following in comp.lang.pytho n:

<rhetorical> Is this the third time this week that this has come
up?
Hey guys, would someone mind giving me a quick rundown of how
references work in Python when passing arguments into functions? The
code below should highlight my specific confusion:
They work just like they do everywhere else...

Read the manuals on mutable and immutable objects. (I'd suggest
language reference chapter 3 and 4, library reference chapter 2.3.6,
2.3.7)

"names" in Python are movable labels attached to objects; they
are not fixed locations in memory to which object are copied; hence they
do not behave like variables in traditional languages.

bool1=True
immutable object -- "bool1" is a label attached to a fixed
object
lst1=[1,2,3]
mutable object -- "lst1" is a label attached to a box
containing objects
def func1(arg1): arg1.append(4)

"arg1" is a label attached to whatever object was passed in...
.append is an operation that changes what is /inside/ that
object
def func2(arg1): arg1=False
"arg1" is a label attached to whatever was passed in...
Assignment (especially of an immutable object) takes that label
OFF of the object that was passed in, and moves it the object of the
assignment. It does not move the label that is outside the call.
func1(lst1)
lst1 [1,2,3,4]

"lst1" is the label of the box; inside of func1, that box has
two labels: "lst1" and "arg1". You used the "arg1" label to locate the
box, and then you changed what was inside the box. Outside the function,
you used the "lst1" label to find the /same/ box and report what was
inside it.
func2(bool1 )
bool1

True

"bool1" is the label of a non-box -- a "true". Inside the
function "true" has initially two labels: "bool1" and "arg1". You then
moved the "arg1" label from "true" to a different object "false".
"bool1" does not move, and still references the "true".
-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Aug 9 '05 #5
Ahh, so it's a mutable thing. That makes sense that I can't change a
mutable object and thus can't affect it outside of the function. Does
that mean Python functions aren't always byref, but are sometimes
byval for nonmutables?

-Greg
On 8/9/05, Dennis Lee Bieber <wl*****@ix.net com.com> wrote:
On Tue, 9 Aug 2005 10:53:15 -0400, Gregory Piñero <gr********@gma il.com>
declaimed the following in comp.lang.pytho n:

<rhetorical> Is this the third time this week that this has come
up?
Hey guys, would someone mind giving me a quick rundown of how
references work in Python when passing arguments into functions? The
code below should highlight my specific confusion:

They work just like they do everywhere else...

Read the manuals on mutable and immutable objects. (I'd suggest
language reference chapter 3 and 4, library reference chapter 2.3.6,
2.3.7)

"names" in Python are movable labels attached to objects; they
are not fixed locations in memory to which object are copied; hence they
do not behave like variables in traditional languages.

bool1=True


immutable object -- "bool1" is a label attached to a fixed
object
lst1=[1,2,3]

mutable object -- "lst1" is a label attached to a box
containing objects
def func1(arg1): arg1.append(4)


"arg1" is a label attached to whatever object was passed in...
.append is an operation that changes what is /inside/ that
object
def func2(arg1): arg1=False

"arg1" is a label attached to whatever was passed in...
Assignment (especially of an immutable object) takes that label
OFF of the object that was passed in, and moves it the object of the
assignment. It does not move the label that is outside the call.
>func1(lst1)
>lst1

[1,2,3,4]

"lst1" is the label of the box; inside of func1, that box has
two labels: "lst1" and "arg1". You used the "arg1" label to locate the
box, and then you changed what was inside the box. Outside the function,
you used the "lst1" label to find the /same/ box and report what was
inside it.
>func2(bool1 )
>bool1

True

"bool1" is the label of a non-box -- a "true". Inside the
function "true" has initially two labels: "bool1" and "arg1". You then
moved the "arg1" label from "true" to a different object "false".
"bool1" does not move, and still references the "true".


--
> =============== =============== =============== =============== == <
> wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
> wu******@dm.net | Bestiaria Support Staff <
> =============== =============== =============== =============== == <
> Home Page: <http://www.dm.net/~wulfraed/ > <
> Overflow Page: <http://wlfraed.home.netcom.com/ > <

--
http://mail.python.org/mailman/listinfo/python-list

--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
Aug 9 '05 #6
Dan
> Does that mean Python functions aren't always byref,
but are sometimes byval for nonmutables?


Don't think of it as byref or byval (as they are used in Visual Basic).
All parameters are passed the same way: by reference instead of by copy.

It's a little difficult to get your head around, but I promise that once
you understand it it will seem simple and intuitive.

def reassign(x):
x = ['foo']

"reassign" has no effect, even on a mutable type like a list. It simply
changes what "x" refers to, which isn't very useful because the name "x"
only exists inside the function.

In Python everything is treated the same way. Even integers are objects:
n = 1
n.__hex__()

'0x1'

What other programming languages do you know? Maybe we can draw a
comparison to something you're familiar with.

--
Presumably, we're all fully qualified computer nerds here,
so we are allowed to use "access" as a verb. Be advised,
however, that the practice in common usage drives
English-language purists to scowling fidgets.
- from Sybex's "Perl, CGI and JavaScript", p. 256
Aug 9 '05 #7
Gregory Piñero wrote:
Ahh, so it's a mutable thing. That makes sense that I can't change a
mutable object and thus can't affect it outside of the function.
If you meant "immutable" for the second mutable, you're right.
Does
that mean Python functions aren't always byref, but are sometimes
byval for nonmutables?


It'd probably do you good to get away from the by reference/by value
thinking. Python isn't C/Basic/Fortran/etc.

Variables in Python are names. They aren't the cubbyholes into which you
put values, they are sticky notes on the front of the cubby hole.

Parameter passing in Python always work the same way - you create a new
name pointing to the passed object. Fin.

The confusion you're having isn't in parameter passing, it's in the
difference between assignment and mutation. Mutation changes the object
itself (what's in the cubby hole), so it doesn't matter what or how many
names/variables it has (what sticky notes are on the front). Assigment
just changes where names point, not the contents of objects. (It's
moving that sticky note, and only that sticky note, from one cubby to a
different one.) Assignment justs affects that name, not any other name
which point to the same object, including the variables in the passing
scope.
Aug 9 '05 #8
On Tue, 09 Aug 2005 10:39:29 -0500, Rocco Moretti
<ro**********@h otpop.com> declaimed the following in comp.lang.pytho n:

Change it to "the object referenced by y is assigned to the name of x",
and you're closer to the truth.
In a more simplistic view, I'd reverse the phrasing... The name
"x" is assigned to the object "y" (implying it is no longer attached to
whatever used to have the name)
-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Aug 9 '05 #9
On Tue, 9 Aug 2005 12:32:15 -0400, Gregory Piñero <gr********@gma il.com>
declaimed the following in comp.lang.pytho n:
Ahh, so it's a mutable thing. That makes sense that I can't change a
mutable object and thus can't affect it outside of the function. Does
that mean Python functions aren't always byref, but are sometimes
byval for nonmutables?
Reverse: boolean constants are immutable and can not be changed,
you can only move the name used to access on to some other object.

If you want to try relating to Visual Basics "byref" "byval",
then they are neither. They are closer to a "copy reference"; changes to
the /reference copy/ do not propagate back out... Changes to the item
the reference, uh, references, do propagate out.

And it doesn't matter what they are referencing... If it is an
object that lets you "go inside to make changes" it is a mutable object,
and operations that "go inside" make no changes to the "reference"
itself.

def sample(l1, l2, l3):
l1.append(4)
l2 = [l2, 4]
l3[1] = 4

a = [1, 2]
b = [3, 4]
c = [5, 6]
sample(a, b, c)

The first line is NOT changing the l1 reference, it is going
inside l1 and changing the insides. "l1" and "a" BOTH reference a list
object that started with [1, 2]. The append opened that object, and
jammed the 4 into it... "a" and "l1" still reference the same list
object, but the list object now has [1, 2, 4]

The second line, OTOH, is changing the l2 reference; it is
creating a new list containing a reference to the object that l2 is
attached to and a reference to a constant 4, THEN it is saying the l2
NOW references the new list -- but since the name l2 only exists inside
the function, it doesn't affect the outside world... "l2" and "b"
initially reference the list object [3, 4]. The assignment first creates
a new list (with no references) of [reference to [3, 4], 4], then "l2"
is changed from a reference to [3, 4] to be a reference to [reference to
[3, 4], 4]; "b" is still a reference to [3, 4]

The third one, again, is opening the referenced object. "c" and
"l3" are references to a list containing [5, 6], "l3[1]" opens the list
and makes the second element 4. "l3" and "c" still reference the same
list.

Now, in that last, it may look like we are changing an immutable
integer. We are not. In all those lists where I have a simple integer:
[5, 6]
the actual list contents are:
[reference to 5, reference to 6]
so that third line is not changing the 6 to a 4, it changing the
"reference to 6" into a "reference to 4"

Names in Python are always (not just in function parameters)
references to objects. An assignment to a name itself always changes the
reference from the old object to a new object. Assignments to qualified
names (l3[1], l1.append(), etc.) are changing the references INSIDE the
object the name references (as long as that object is a mutable object),
but do not change the reference of the name.
-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Aug 9 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
6375
by: Martin Lucas-Smith | last post by:
Having re-read www.php.net/functions.arguments recently, the notion of passing arguments by reference to a function makes a lot more sense now. However, my question is: is there any difference in outcome between: function add_some_extra(&$string) { $string .= 'and something extra.'; }
40
3391
by: Sonia | last post by:
Hi, Please look at the following code. This is a simple program for a game of craps - very basic. I have declared the gameStatus as global variable. I was wondering if there is a better way of handling this (possibly via local variables) I am using that variable to keep track of the status of the game and pass it back to main() from craps() where I either increase or decrease a bank balance. Should this be handled with local parameters...
34
7107
by: yensao | last post by:
Hi, I have a hard time to understand difference and similarities between Relational database model and the Object-Oriented model. Can somebody help me with this? Thank you in advance. Yensao
3
14946
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
39
7663
by: Mike MacSween | last post by:
Just spent a happy 10 mins trying to understand a function I wrote sometime ago. Then remembered that arguments are passed by reference, by default. Does the fact that this slowed me down indicate: a) That I don't know enough b) Passing arguments by ref is bad
12
6903
by: Dennis D. | last post by:
Hello: I want a function to return three variables to the calling procedure: Private Function CalcTimes(ByVal iAddDays as Integer, ByVal iAddHours as Integer, ByVal iAddMins as Integer) As Array Variable values are calculated in the function. Calling procedure receives the values preferably into variables of the same
3
4123
by: Matt | last post by:
Hi All, I have the current Sub Procedure in a VBA Module. ----------------------------------------------------------------------------------------------------------------------------- Sub openForm(formName As String, Optional varToSend As Object) If varToSend Is Missing Then DoCmd.openForm formName Else DoCmd.openForm formName, , , , , , varToSend
3
5468
by: Subodh | last post by:
Hi All, In C++ we could pass a constant reference to a function so that the target function could not modify the objects passed eg. const classA & dummmyfunction(const classB) similar thing was valid for objects passed with pointer to constant objects In C++/CLI is there any way for imitating this, I want to pass arguments to and return value from my member function as a constant
9
5276
by: oldyork90 | last post by:
I'm going thru code and have never seen this before http://www.webreference.com/programming/javascript/mk/column2/3.html Look at function CreateDragContainer() on line 25. It has no arguments defined and depends on a function property named arguments to process its input. I poked around and found this is deprecated. How do you pass an unknown number of arguments to a function? Put them in an array?
0
9000
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9577
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9396
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9339
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6804
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6081
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4713
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2804
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.