top button
Flag Notify
Site Registration

How to pass variable by reference in Python?

+1 vote
667 views
How to pass variable by reference in Python?
posted May 6, 2014 by Satish Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

Python provides neither pass-by-reference nor pass-by-value argument passing. Please read this for an explanation of why people sometimes think that it does, and what Python actually does instead:

http://import-that.dreamwidth.org/1130.html

To get an effect *similar* to pass-by-reference, you can wrap your variable in a list, and then only operate on the list item. For example:

one = [1]
two = [2]

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

swap(one, two)
print one[0], two[0]
=> will print "2 1"

But note carefully that in the swap function I do not assign directly to the arguments a and b, only to their items a[0] and b[0]. If you assign directly to a and b, you change the local variables.

# This does not work.
def swap(a, b):
 a, b = b, a

Rather than trying to fake pass-by-reference semantics, it is much better to understand Python's capabilities and learn how to use it to get the same effect. For example, instead of writing a swap procedure, it is much simpler to just do this:

one = 1
two = 2
one, two = two, one
print one, two
=> will print "2 1"
answer May 6, 2014 by Amit Parthsarthi
+1 vote
answer May 6, 2014 by Sheetal Chauhan
Similar Questions
+1 vote

My code has this structure:

class Example(wx.Frame,listmix.ColumnSorterMixin):
 def __init__(self,parent):
 wx.Frame.__init__(self,parent)

 self.InitUI()

 def InitUI(self): 
 ..... 

when a button is clicked this function is called and i take the self.id_number which is a number

 def OnB(self, event):
 self.id_number = self.text_ctrl_number.GetValue()
 aa = latitude[int(self.id_number)]
 bb = longitude[int(self.id_number)]

I want to pass the variables aa and bb to a different script called application. This script by calling it with import, automatically pop up a window. I need by clicking the button that is linked with OnB definition to pop up the window from the other script as it does when i am running it alone and display lets say for example the variables aa and bb, how can I do it

...