Python: Keep changes on a variable made within a function









up vote
-1
down vote

favorite












I have a question on a fairly simple task in python, however, I didn't manage to find a solution. I would like to assign a new value to an already existing variable in python. However, the changes I am doing to the variable within the function don't stick to the variable.



Here is a simplified example of my problem:



y = 1
x = None

def test(var):

var = y

return var


test(x)
print(x)


The print simply returns none. So the changes I have done to the variable within the function are non permanent.



How can I make the changes on the input-variable of the function permanent?



Thanks in advance!










share|improve this question





















  • write x = test(x).. instad of test(x).
    – mehrdad-pedramfar
    Nov 11 at 14:48











  • You only ever change the var variable, what else do you expect to change?
    – MisterMiyagi
    Nov 11 at 14:52










  • You did not change the variable, you created a new one with the same name.
    – Klaus D.
    Nov 11 at 14:52










  • Your question is unclear. Do you mean x = test(x)?
    – Daniel Roseman
    Nov 11 at 15:03










  • Possible duplicate of How do I pass a variable by reference?
    – barbsan
    Nov 11 at 23:43














up vote
-1
down vote

favorite












I have a question on a fairly simple task in python, however, I didn't manage to find a solution. I would like to assign a new value to an already existing variable in python. However, the changes I am doing to the variable within the function don't stick to the variable.



Here is a simplified example of my problem:



y = 1
x = None

def test(var):

var = y

return var


test(x)
print(x)


The print simply returns none. So the changes I have done to the variable within the function are non permanent.



How can I make the changes on the input-variable of the function permanent?



Thanks in advance!










share|improve this question





















  • write x = test(x).. instad of test(x).
    – mehrdad-pedramfar
    Nov 11 at 14:48











  • You only ever change the var variable, what else do you expect to change?
    – MisterMiyagi
    Nov 11 at 14:52










  • You did not change the variable, you created a new one with the same name.
    – Klaus D.
    Nov 11 at 14:52










  • Your question is unclear. Do you mean x = test(x)?
    – Daniel Roseman
    Nov 11 at 15:03










  • Possible duplicate of How do I pass a variable by reference?
    – barbsan
    Nov 11 at 23:43












up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I have a question on a fairly simple task in python, however, I didn't manage to find a solution. I would like to assign a new value to an already existing variable in python. However, the changes I am doing to the variable within the function don't stick to the variable.



Here is a simplified example of my problem:



y = 1
x = None

def test(var):

var = y

return var


test(x)
print(x)


The print simply returns none. So the changes I have done to the variable within the function are non permanent.



How can I make the changes on the input-variable of the function permanent?



Thanks in advance!










share|improve this question













I have a question on a fairly simple task in python, however, I didn't manage to find a solution. I would like to assign a new value to an already existing variable in python. However, the changes I am doing to the variable within the function don't stick to the variable.



Here is a simplified example of my problem:



y = 1
x = None

def test(var):

var = y

return var


test(x)
print(x)


The print simply returns none. So the changes I have done to the variable within the function are non permanent.



How can I make the changes on the input-variable of the function permanent?



Thanks in advance!







python function variables






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 14:46









ZeroStrikeCall

111




111











  • write x = test(x).. instad of test(x).
    – mehrdad-pedramfar
    Nov 11 at 14:48











  • You only ever change the var variable, what else do you expect to change?
    – MisterMiyagi
    Nov 11 at 14:52










  • You did not change the variable, you created a new one with the same name.
    – Klaus D.
    Nov 11 at 14:52










  • Your question is unclear. Do you mean x = test(x)?
    – Daniel Roseman
    Nov 11 at 15:03










  • Possible duplicate of How do I pass a variable by reference?
    – barbsan
    Nov 11 at 23:43
















  • write x = test(x).. instad of test(x).
    – mehrdad-pedramfar
    Nov 11 at 14:48











  • You only ever change the var variable, what else do you expect to change?
    – MisterMiyagi
    Nov 11 at 14:52










  • You did not change the variable, you created a new one with the same name.
    – Klaus D.
    Nov 11 at 14:52










  • Your question is unclear. Do you mean x = test(x)?
    – Daniel Roseman
    Nov 11 at 15:03










  • Possible duplicate of How do I pass a variable by reference?
    – barbsan
    Nov 11 at 23:43















write x = test(x).. instad of test(x).
– mehrdad-pedramfar
Nov 11 at 14:48





write x = test(x).. instad of test(x).
– mehrdad-pedramfar
Nov 11 at 14:48













You only ever change the var variable, what else do you expect to change?
– MisterMiyagi
Nov 11 at 14:52




You only ever change the var variable, what else do you expect to change?
– MisterMiyagi
Nov 11 at 14:52












You did not change the variable, you created a new one with the same name.
– Klaus D.
Nov 11 at 14:52




You did not change the variable, you created a new one with the same name.
– Klaus D.
Nov 11 at 14:52












Your question is unclear. Do you mean x = test(x)?
– Daniel Roseman
Nov 11 at 15:03




Your question is unclear. Do you mean x = test(x)?
– Daniel Roseman
Nov 11 at 15:03












Possible duplicate of How do I pass a variable by reference?
– barbsan
Nov 11 at 23:43




Possible duplicate of How do I pass a variable by reference?
– barbsan
Nov 11 at 23:43












2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










This is an example of passing variables to functions by value. By default, when you pass a variable to a function in Python, it is passed by value.



What it means is, that a new variable with a new scope is created with the same value of x. So, any change that happens to the new x is not reflected to the x outside the function's scope.



If you want to get the value from the function back, you can use the return statement (as you have used). return returns the value back from the function. However, in your example there is no variable to receive it. Hence, it is lost.



You would have to call the function as x = test(x). This ensures that x receives the value back from the function.






share|improve this answer






















  • Python has only one type of variable, and they are always passed the same way.
    – MisterMiyagi
    Nov 11 at 15:07










  • Ahh. I always get confused between Python and C. Lemme fix that. :P
    – MaJoR
    Nov 11 at 15:09

















up vote
0
down vote













Variables in Python are just names which refer to objects. In an expression, the name is a stand-in for the actual object. Saying test(x) means "pass the object referred to by x into test". It does not mean "pass the symbol x into test".



In addition, re-assigning a name only changes what object that name refers to. It affects neither the object nor any of its aliases.



In short, the name var you modify inside test has no relation to x at all.




The preferred way to have a function change something is by reassigning the result:



x = 2
def change(var):
return var * 2

x = change(x) # x now refers to 4 instead of 2
print(x)



If you want to change a name outside a function, you can use the nonlocal and global keywords:



x = 2
def change_x():
global x
x = x * 2

change_x() # x now refers to 4 instead of 2
print(x)


While this can make some trivial problems easy to solve, it is generally a bad idea for larger programs. Using global variables means one can no longer use the function in isolation; results may depend on how often and in what order such a function is called.




If you have some self-contained group of values and means to modify them, a class can be used to describe this:



class XY:
def __init__(self, x, y):
self.x, self.y = x, y

def swap(self):
self.x, self.y = self.y, self.x

my_values = XY(None, 1)
print(my_values.x, my_values.y)
my_values.swap()
print(my_values.x, my_values.y)


In contrast to global variables, you can create as many isolated instances of classes as needed. Each instance can be worked on in isolation, without affecting the others.




You can also mutable values to make changes visible to the outside. Instead of changing the name, you modify the value.



x = [2] # x is a mutable list, containing the value 2 at the moment
def change(var):
var[0] = 4

change(x) # x now contains 4 instead of 2
print(x)





share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249829%2fpython-keep-changes-on-a-variable-made-within-a-function%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    This is an example of passing variables to functions by value. By default, when you pass a variable to a function in Python, it is passed by value.



    What it means is, that a new variable with a new scope is created with the same value of x. So, any change that happens to the new x is not reflected to the x outside the function's scope.



    If you want to get the value from the function back, you can use the return statement (as you have used). return returns the value back from the function. However, in your example there is no variable to receive it. Hence, it is lost.



    You would have to call the function as x = test(x). This ensures that x receives the value back from the function.






    share|improve this answer






















    • Python has only one type of variable, and they are always passed the same way.
      – MisterMiyagi
      Nov 11 at 15:07










    • Ahh. I always get confused between Python and C. Lemme fix that. :P
      – MaJoR
      Nov 11 at 15:09














    up vote
    0
    down vote



    accepted










    This is an example of passing variables to functions by value. By default, when you pass a variable to a function in Python, it is passed by value.



    What it means is, that a new variable with a new scope is created with the same value of x. So, any change that happens to the new x is not reflected to the x outside the function's scope.



    If you want to get the value from the function back, you can use the return statement (as you have used). return returns the value back from the function. However, in your example there is no variable to receive it. Hence, it is lost.



    You would have to call the function as x = test(x). This ensures that x receives the value back from the function.






    share|improve this answer






















    • Python has only one type of variable, and they are always passed the same way.
      – MisterMiyagi
      Nov 11 at 15:07










    • Ahh. I always get confused between Python and C. Lemme fix that. :P
      – MaJoR
      Nov 11 at 15:09












    up vote
    0
    down vote



    accepted







    up vote
    0
    down vote



    accepted






    This is an example of passing variables to functions by value. By default, when you pass a variable to a function in Python, it is passed by value.



    What it means is, that a new variable with a new scope is created with the same value of x. So, any change that happens to the new x is not reflected to the x outside the function's scope.



    If you want to get the value from the function back, you can use the return statement (as you have used). return returns the value back from the function. However, in your example there is no variable to receive it. Hence, it is lost.



    You would have to call the function as x = test(x). This ensures that x receives the value back from the function.






    share|improve this answer














    This is an example of passing variables to functions by value. By default, when you pass a variable to a function in Python, it is passed by value.



    What it means is, that a new variable with a new scope is created with the same value of x. So, any change that happens to the new x is not reflected to the x outside the function's scope.



    If you want to get the value from the function back, you can use the return statement (as you have used). return returns the value back from the function. However, in your example there is no variable to receive it. Hence, it is lost.



    You would have to call the function as x = test(x). This ensures that x receives the value back from the function.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 11 at 15:10

























    answered Nov 11 at 15:05









    MaJoR

    402111




    402111











    • Python has only one type of variable, and they are always passed the same way.
      – MisterMiyagi
      Nov 11 at 15:07










    • Ahh. I always get confused between Python and C. Lemme fix that. :P
      – MaJoR
      Nov 11 at 15:09
















    • Python has only one type of variable, and they are always passed the same way.
      – MisterMiyagi
      Nov 11 at 15:07










    • Ahh. I always get confused between Python and C. Lemme fix that. :P
      – MaJoR
      Nov 11 at 15:09















    Python has only one type of variable, and they are always passed the same way.
    – MisterMiyagi
    Nov 11 at 15:07




    Python has only one type of variable, and they are always passed the same way.
    – MisterMiyagi
    Nov 11 at 15:07












    Ahh. I always get confused between Python and C. Lemme fix that. :P
    – MaJoR
    Nov 11 at 15:09




    Ahh. I always get confused between Python and C. Lemme fix that. :P
    – MaJoR
    Nov 11 at 15:09












    up vote
    0
    down vote













    Variables in Python are just names which refer to objects. In an expression, the name is a stand-in for the actual object. Saying test(x) means "pass the object referred to by x into test". It does not mean "pass the symbol x into test".



    In addition, re-assigning a name only changes what object that name refers to. It affects neither the object nor any of its aliases.



    In short, the name var you modify inside test has no relation to x at all.




    The preferred way to have a function change something is by reassigning the result:



    x = 2
    def change(var):
    return var * 2

    x = change(x) # x now refers to 4 instead of 2
    print(x)



    If you want to change a name outside a function, you can use the nonlocal and global keywords:



    x = 2
    def change_x():
    global x
    x = x * 2

    change_x() # x now refers to 4 instead of 2
    print(x)


    While this can make some trivial problems easy to solve, it is generally a bad idea for larger programs. Using global variables means one can no longer use the function in isolation; results may depend on how often and in what order such a function is called.




    If you have some self-contained group of values and means to modify them, a class can be used to describe this:



    class XY:
    def __init__(self, x, y):
    self.x, self.y = x, y

    def swap(self):
    self.x, self.y = self.y, self.x

    my_values = XY(None, 1)
    print(my_values.x, my_values.y)
    my_values.swap()
    print(my_values.x, my_values.y)


    In contrast to global variables, you can create as many isolated instances of classes as needed. Each instance can be worked on in isolation, without affecting the others.




    You can also mutable values to make changes visible to the outside. Instead of changing the name, you modify the value.



    x = [2] # x is a mutable list, containing the value 2 at the moment
    def change(var):
    var[0] = 4

    change(x) # x now contains 4 instead of 2
    print(x)





    share|improve this answer


























      up vote
      0
      down vote













      Variables in Python are just names which refer to objects. In an expression, the name is a stand-in for the actual object. Saying test(x) means "pass the object referred to by x into test". It does not mean "pass the symbol x into test".



      In addition, re-assigning a name only changes what object that name refers to. It affects neither the object nor any of its aliases.



      In short, the name var you modify inside test has no relation to x at all.




      The preferred way to have a function change something is by reassigning the result:



      x = 2
      def change(var):
      return var * 2

      x = change(x) # x now refers to 4 instead of 2
      print(x)



      If you want to change a name outside a function, you can use the nonlocal and global keywords:



      x = 2
      def change_x():
      global x
      x = x * 2

      change_x() # x now refers to 4 instead of 2
      print(x)


      While this can make some trivial problems easy to solve, it is generally a bad idea for larger programs. Using global variables means one can no longer use the function in isolation; results may depend on how often and in what order such a function is called.




      If you have some self-contained group of values and means to modify them, a class can be used to describe this:



      class XY:
      def __init__(self, x, y):
      self.x, self.y = x, y

      def swap(self):
      self.x, self.y = self.y, self.x

      my_values = XY(None, 1)
      print(my_values.x, my_values.y)
      my_values.swap()
      print(my_values.x, my_values.y)


      In contrast to global variables, you can create as many isolated instances of classes as needed. Each instance can be worked on in isolation, without affecting the others.




      You can also mutable values to make changes visible to the outside. Instead of changing the name, you modify the value.



      x = [2] # x is a mutable list, containing the value 2 at the moment
      def change(var):
      var[0] = 4

      change(x) # x now contains 4 instead of 2
      print(x)





      share|improve this answer
























        up vote
        0
        down vote










        up vote
        0
        down vote









        Variables in Python are just names which refer to objects. In an expression, the name is a stand-in for the actual object. Saying test(x) means "pass the object referred to by x into test". It does not mean "pass the symbol x into test".



        In addition, re-assigning a name only changes what object that name refers to. It affects neither the object nor any of its aliases.



        In short, the name var you modify inside test has no relation to x at all.




        The preferred way to have a function change something is by reassigning the result:



        x = 2
        def change(var):
        return var * 2

        x = change(x) # x now refers to 4 instead of 2
        print(x)



        If you want to change a name outside a function, you can use the nonlocal and global keywords:



        x = 2
        def change_x():
        global x
        x = x * 2

        change_x() # x now refers to 4 instead of 2
        print(x)


        While this can make some trivial problems easy to solve, it is generally a bad idea for larger programs. Using global variables means one can no longer use the function in isolation; results may depend on how often and in what order such a function is called.




        If you have some self-contained group of values and means to modify them, a class can be used to describe this:



        class XY:
        def __init__(self, x, y):
        self.x, self.y = x, y

        def swap(self):
        self.x, self.y = self.y, self.x

        my_values = XY(None, 1)
        print(my_values.x, my_values.y)
        my_values.swap()
        print(my_values.x, my_values.y)


        In contrast to global variables, you can create as many isolated instances of classes as needed. Each instance can be worked on in isolation, without affecting the others.




        You can also mutable values to make changes visible to the outside. Instead of changing the name, you modify the value.



        x = [2] # x is a mutable list, containing the value 2 at the moment
        def change(var):
        var[0] = 4

        change(x) # x now contains 4 instead of 2
        print(x)





        share|improve this answer














        Variables in Python are just names which refer to objects. In an expression, the name is a stand-in for the actual object. Saying test(x) means "pass the object referred to by x into test". It does not mean "pass the symbol x into test".



        In addition, re-assigning a name only changes what object that name refers to. It affects neither the object nor any of its aliases.



        In short, the name var you modify inside test has no relation to x at all.




        The preferred way to have a function change something is by reassigning the result:



        x = 2
        def change(var):
        return var * 2

        x = change(x) # x now refers to 4 instead of 2
        print(x)



        If you want to change a name outside a function, you can use the nonlocal and global keywords:



        x = 2
        def change_x():
        global x
        x = x * 2

        change_x() # x now refers to 4 instead of 2
        print(x)


        While this can make some trivial problems easy to solve, it is generally a bad idea for larger programs. Using global variables means one can no longer use the function in isolation; results may depend on how often and in what order such a function is called.




        If you have some self-contained group of values and means to modify them, a class can be used to describe this:



        class XY:
        def __init__(self, x, y):
        self.x, self.y = x, y

        def swap(self):
        self.x, self.y = self.y, self.x

        my_values = XY(None, 1)
        print(my_values.x, my_values.y)
        my_values.swap()
        print(my_values.x, my_values.y)


        In contrast to global variables, you can create as many isolated instances of classes as needed. Each instance can be worked on in isolation, without affecting the others.




        You can also mutable values to make changes visible to the outside. Instead of changing the name, you modify the value.



        x = [2] # x is a mutable list, containing the value 2 at the moment
        def change(var):
        var[0] = 4

        change(x) # x now contains 4 instead of 2
        print(x)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 11 at 15:48

























        answered Nov 11 at 15:38









        MisterMiyagi

        7,2242040




        7,2242040



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249829%2fpython-keep-changes-on-a-variable-made-within-a-function%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            政党

            天津地下鉄3号線