Python list doesn't reflect variable change












17















When I write this code:



polly = "alive"
palin = ["parrot", polly]
print(palin)
polly = "dead"
print(palin)


I thought it would output this:



"['parrot', 'alive']"
"['parrot', 'dead']"


However, it doesn't. How do I get it to output that?










share|improve this question




















  • 2





    related : stackoverflow.com/q/11690220/748858

    – mgilson
    Aug 22 '12 at 20:09
















17















When I write this code:



polly = "alive"
palin = ["parrot", polly]
print(palin)
polly = "dead"
print(palin)


I thought it would output this:



"['parrot', 'alive']"
"['parrot', 'dead']"


However, it doesn't. How do I get it to output that?










share|improve this question




















  • 2





    related : stackoverflow.com/q/11690220/748858

    – mgilson
    Aug 22 '12 at 20:09














17












17








17


7






When I write this code:



polly = "alive"
palin = ["parrot", polly]
print(palin)
polly = "dead"
print(palin)


I thought it would output this:



"['parrot', 'alive']"
"['parrot', 'dead']"


However, it doesn't. How do I get it to output that?










share|improve this question
















When I write this code:



polly = "alive"
palin = ["parrot", polly]
print(palin)
polly = "dead"
print(palin)


I thought it would output this:



"['parrot', 'alive']"
"['parrot', 'dead']"


However, it doesn't. How do I get it to output that?







python list variables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 27 '13 at 2:21







user212218

















asked Aug 22 '12 at 20:01









Flexo1515Flexo1515

5091622




5091622








  • 2





    related : stackoverflow.com/q/11690220/748858

    – mgilson
    Aug 22 '12 at 20:09














  • 2





    related : stackoverflow.com/q/11690220/748858

    – mgilson
    Aug 22 '12 at 20:09








2




2





related : stackoverflow.com/q/11690220/748858

– mgilson
Aug 22 '12 at 20:09





related : stackoverflow.com/q/11690220/748858

– mgilson
Aug 22 '12 at 20:09












6 Answers
6






active

oldest

votes


















46














Python variables hold references to values. Thus, when you define the palin list, you pass in the value referenced by polly, not the variable itself.



You should imagine values as balloons, with variables being threads tied to those balloons. "alive" is a balloon, polly is just a thread to that balloon, and the palin list has a different thread tied to that same balloon. In python, a list is simply a series of threads, all numbered starting at 0.



What you do next is tie the polly string to a new balloon "dead", but the list is still holding on to the old thread tied to the "alive" balloon.



You can replace that thread to "alive" held by the list by reassigning the list by index to refer to each thread; in your example that's thread 1:



>>> palin[1] = polly
>>> palin
['parrot', 'dead']


Here I simply tied the palin[1] thread to the same thing polly is tied to, whatever that might be.



Note that any collection in python, such as dict, set, tuple, etc. are simply collections of threads too. Some of these can have their threads swapped out for different threads, such as lists and dicts, and that's what makes something in python "mutable".



Strings on the other hand, are not mutable. Once you define a string like "dead" or "alive", it's one balloon. You can tie it down with a thread (a variable, a list, or whatever), but you cannot replace letters inside of it. You can only tie that thread to a completely new string.



Most things in python can act like balloons. Integers, strings, lists, functions, instances, classes, all can be tied down to a variable, or tied into a container.



You may want to read Ned Batchelder's treatise on Python names too.






share|improve this answer


























  • Thank you, I believe now that I asked the incorrect question but thank you

    – Flexo1515
    Aug 22 '12 at 20:13






  • 11





    I like the balloon analogy -- especially if they're helium balloons which float away when the last string is released... (+1).

    – mgilson
    Aug 22 '12 at 20:14








  • 4





    Does this mean garbage collection strategies correspond to weather?

    – DSM
    Aug 22 '12 at 20:18






  • 8





    @DSM: Exactly :-) GC is the wind that blows away any balloons not tied down. :-)

    – Martijn Pieters
    Aug 22 '12 at 20:19






  • 1





    @user1404053: then you need a mutable balloon. A user-defined class, for example, instead of a string.

    – Martijn Pieters
    Aug 22 '12 at 20:23



















4














Before your second print statement, store your new values into palin:



palin = ["parrot", polly]





share|improve this answer
























  • Anyway to do it without restoring the new value?

    – Flexo1515
    Aug 22 '12 at 20:07






  • 3





    @user1404053: Not the way you're asking. In Python strings are immutable, so there's no way to change the value in polly and therefore change it everywhere else. The line polly = "dead" is a rebinding operation rather than a mutating one

    – David Robinson
    Aug 22 '12 at 20:11



















3














When you put a string in a list, the list holds a copy of the string. It doesn't matter whether the string was originally a variable, a literal value, the result of a function call, or something else; by the time the list sees it, it's just a string value. Changing whatever generated the string later will never affect the list.



If you want to store a reference to a value that will notice when that value changes, the usual mechanism is to use a list containing the "referenced" value. Applying that to your example, you wind up with a nested list:



polly = ["alive"]
palin = ["parrot", polly]
print(palin)
polly[0] = "dead"
print(palin)





share|improve this answer































    1














    The list will contain values only, not references to variables as you would like. You could however store a lambda in the list, and have the lambda look up the value of your variable.



    >>> a = 'a'
    >>> list = ['a',lambda: a]
    >>> list[1]
    <function <lambda> at 0x7feff71dc500>
    >>> list[1]()
    'a'
    >>> a = 'b'
    >>> list[1]()
    'b'





    share|improve this answer
























    • Some more explanation: here lambda: a is basically a function that just returns the value stored in a. That's why you can use the command list[1](); it means you call the function stored in list[1]. (Also, appropriate gravatar, @Jonatan)

      – Matthew Adams
      Aug 22 '12 at 20:17











    • Quite right, thanks for the explanation. Also I had completely forgotten my avatar, haha!

      – Jonatan
      Aug 22 '12 at 20:20



















    0














    You can't. Assignment to a bare name is Python always only rebinds the name, and you cannot customize or monitor this operation.



    What you can do is make polly a mutable object instead of a string, and mutate its value instead of rebinding the name. A simple example:



    >>> polly = ['alive']
    >>> items = ['parrot', polly]
    >>> items
    ['parrot', ['alive']]
    >>> polly[0] = 'dead'
    >>> items
    ['parrot', ['dead']]





    share|improve this answer































      0














      The other answers have explained what's going on well.



      This is one of the (several) problems that motivate the use of objects. For example, one might do this:



      class Animal:
      def __init__(self, aniType, name):
      self.aniType = aniType
      self.name = name
      self.isAlive = True

      def kill(self):
      self.isAlive = False

      def getName(self):
      return self.name

      def getType(self):
      return self.aniType

      def isLiving(self):
      return self.isAlive


      polly = Animal("parrot", "polly")

      print(polly.getName()+' the '+polly.getType()+' is alive?')
      print(polly.isLiving())

      polly.kill()

      print(polly.getName()+' the '+polly.getType()+' is alive?')
      print(polly.isLiving())


      It may look like a lot of code at first for a simple task, but objects are often the way to go for things like this, because they help keep everything organized.



      Here's the output of that program:



      polly the parrot is alive?
      True
      polly the parrot is alive?
      False





      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',
        autoActivateHeartbeat: false,
        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%2f12080552%2fpython-list-doesnt-reflect-variable-change%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        46














        Python variables hold references to values. Thus, when you define the palin list, you pass in the value referenced by polly, not the variable itself.



        You should imagine values as balloons, with variables being threads tied to those balloons. "alive" is a balloon, polly is just a thread to that balloon, and the palin list has a different thread tied to that same balloon. In python, a list is simply a series of threads, all numbered starting at 0.



        What you do next is tie the polly string to a new balloon "dead", but the list is still holding on to the old thread tied to the "alive" balloon.



        You can replace that thread to "alive" held by the list by reassigning the list by index to refer to each thread; in your example that's thread 1:



        >>> palin[1] = polly
        >>> palin
        ['parrot', 'dead']


        Here I simply tied the palin[1] thread to the same thing polly is tied to, whatever that might be.



        Note that any collection in python, such as dict, set, tuple, etc. are simply collections of threads too. Some of these can have their threads swapped out for different threads, such as lists and dicts, and that's what makes something in python "mutable".



        Strings on the other hand, are not mutable. Once you define a string like "dead" or "alive", it's one balloon. You can tie it down with a thread (a variable, a list, or whatever), but you cannot replace letters inside of it. You can only tie that thread to a completely new string.



        Most things in python can act like balloons. Integers, strings, lists, functions, instances, classes, all can be tied down to a variable, or tied into a container.



        You may want to read Ned Batchelder's treatise on Python names too.






        share|improve this answer


























        • Thank you, I believe now that I asked the incorrect question but thank you

          – Flexo1515
          Aug 22 '12 at 20:13






        • 11





          I like the balloon analogy -- especially if they're helium balloons which float away when the last string is released... (+1).

          – mgilson
          Aug 22 '12 at 20:14








        • 4





          Does this mean garbage collection strategies correspond to weather?

          – DSM
          Aug 22 '12 at 20:18






        • 8





          @DSM: Exactly :-) GC is the wind that blows away any balloons not tied down. :-)

          – Martijn Pieters
          Aug 22 '12 at 20:19






        • 1





          @user1404053: then you need a mutable balloon. A user-defined class, for example, instead of a string.

          – Martijn Pieters
          Aug 22 '12 at 20:23
















        46














        Python variables hold references to values. Thus, when you define the palin list, you pass in the value referenced by polly, not the variable itself.



        You should imagine values as balloons, with variables being threads tied to those balloons. "alive" is a balloon, polly is just a thread to that balloon, and the palin list has a different thread tied to that same balloon. In python, a list is simply a series of threads, all numbered starting at 0.



        What you do next is tie the polly string to a new balloon "dead", but the list is still holding on to the old thread tied to the "alive" balloon.



        You can replace that thread to "alive" held by the list by reassigning the list by index to refer to each thread; in your example that's thread 1:



        >>> palin[1] = polly
        >>> palin
        ['parrot', 'dead']


        Here I simply tied the palin[1] thread to the same thing polly is tied to, whatever that might be.



        Note that any collection in python, such as dict, set, tuple, etc. are simply collections of threads too. Some of these can have their threads swapped out for different threads, such as lists and dicts, and that's what makes something in python "mutable".



        Strings on the other hand, are not mutable. Once you define a string like "dead" or "alive", it's one balloon. You can tie it down with a thread (a variable, a list, or whatever), but you cannot replace letters inside of it. You can only tie that thread to a completely new string.



        Most things in python can act like balloons. Integers, strings, lists, functions, instances, classes, all can be tied down to a variable, or tied into a container.



        You may want to read Ned Batchelder's treatise on Python names too.






        share|improve this answer


























        • Thank you, I believe now that I asked the incorrect question but thank you

          – Flexo1515
          Aug 22 '12 at 20:13






        • 11





          I like the balloon analogy -- especially if they're helium balloons which float away when the last string is released... (+1).

          – mgilson
          Aug 22 '12 at 20:14








        • 4





          Does this mean garbage collection strategies correspond to weather?

          – DSM
          Aug 22 '12 at 20:18






        • 8





          @DSM: Exactly :-) GC is the wind that blows away any balloons not tied down. :-)

          – Martijn Pieters
          Aug 22 '12 at 20:19






        • 1





          @user1404053: then you need a mutable balloon. A user-defined class, for example, instead of a string.

          – Martijn Pieters
          Aug 22 '12 at 20:23














        46












        46








        46







        Python variables hold references to values. Thus, when you define the palin list, you pass in the value referenced by polly, not the variable itself.



        You should imagine values as balloons, with variables being threads tied to those balloons. "alive" is a balloon, polly is just a thread to that balloon, and the palin list has a different thread tied to that same balloon. In python, a list is simply a series of threads, all numbered starting at 0.



        What you do next is tie the polly string to a new balloon "dead", but the list is still holding on to the old thread tied to the "alive" balloon.



        You can replace that thread to "alive" held by the list by reassigning the list by index to refer to each thread; in your example that's thread 1:



        >>> palin[1] = polly
        >>> palin
        ['parrot', 'dead']


        Here I simply tied the palin[1] thread to the same thing polly is tied to, whatever that might be.



        Note that any collection in python, such as dict, set, tuple, etc. are simply collections of threads too. Some of these can have their threads swapped out for different threads, such as lists and dicts, and that's what makes something in python "mutable".



        Strings on the other hand, are not mutable. Once you define a string like "dead" or "alive", it's one balloon. You can tie it down with a thread (a variable, a list, or whatever), but you cannot replace letters inside of it. You can only tie that thread to a completely new string.



        Most things in python can act like balloons. Integers, strings, lists, functions, instances, classes, all can be tied down to a variable, or tied into a container.



        You may want to read Ned Batchelder's treatise on Python names too.






        share|improve this answer















        Python variables hold references to values. Thus, when you define the palin list, you pass in the value referenced by polly, not the variable itself.



        You should imagine values as balloons, with variables being threads tied to those balloons. "alive" is a balloon, polly is just a thread to that balloon, and the palin list has a different thread tied to that same balloon. In python, a list is simply a series of threads, all numbered starting at 0.



        What you do next is tie the polly string to a new balloon "dead", but the list is still holding on to the old thread tied to the "alive" balloon.



        You can replace that thread to "alive" held by the list by reassigning the list by index to refer to each thread; in your example that's thread 1:



        >>> palin[1] = polly
        >>> palin
        ['parrot', 'dead']


        Here I simply tied the palin[1] thread to the same thing polly is tied to, whatever that might be.



        Note that any collection in python, such as dict, set, tuple, etc. are simply collections of threads too. Some of these can have their threads swapped out for different threads, such as lists and dicts, and that's what makes something in python "mutable".



        Strings on the other hand, are not mutable. Once you define a string like "dead" or "alive", it's one balloon. You can tie it down with a thread (a variable, a list, or whatever), but you cannot replace letters inside of it. You can only tie that thread to a completely new string.



        Most things in python can act like balloons. Integers, strings, lists, functions, instances, classes, all can be tied down to a variable, or tied into a container.



        You may want to read Ned Batchelder's treatise on Python names too.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Sep 27 '16 at 11:36

























        answered Aug 22 '12 at 20:09









        Martijn PietersMartijn Pieters

        710k13724782299




        710k13724782299













        • Thank you, I believe now that I asked the incorrect question but thank you

          – Flexo1515
          Aug 22 '12 at 20:13






        • 11





          I like the balloon analogy -- especially if they're helium balloons which float away when the last string is released... (+1).

          – mgilson
          Aug 22 '12 at 20:14








        • 4





          Does this mean garbage collection strategies correspond to weather?

          – DSM
          Aug 22 '12 at 20:18






        • 8





          @DSM: Exactly :-) GC is the wind that blows away any balloons not tied down. :-)

          – Martijn Pieters
          Aug 22 '12 at 20:19






        • 1





          @user1404053: then you need a mutable balloon. A user-defined class, for example, instead of a string.

          – Martijn Pieters
          Aug 22 '12 at 20:23



















        • Thank you, I believe now that I asked the incorrect question but thank you

          – Flexo1515
          Aug 22 '12 at 20:13






        • 11





          I like the balloon analogy -- especially if they're helium balloons which float away when the last string is released... (+1).

          – mgilson
          Aug 22 '12 at 20:14








        • 4





          Does this mean garbage collection strategies correspond to weather?

          – DSM
          Aug 22 '12 at 20:18






        • 8





          @DSM: Exactly :-) GC is the wind that blows away any balloons not tied down. :-)

          – Martijn Pieters
          Aug 22 '12 at 20:19






        • 1





          @user1404053: then you need a mutable balloon. A user-defined class, for example, instead of a string.

          – Martijn Pieters
          Aug 22 '12 at 20:23

















        Thank you, I believe now that I asked the incorrect question but thank you

        – Flexo1515
        Aug 22 '12 at 20:13





        Thank you, I believe now that I asked the incorrect question but thank you

        – Flexo1515
        Aug 22 '12 at 20:13




        11




        11





        I like the balloon analogy -- especially if they're helium balloons which float away when the last string is released... (+1).

        – mgilson
        Aug 22 '12 at 20:14







        I like the balloon analogy -- especially if they're helium balloons which float away when the last string is released... (+1).

        – mgilson
        Aug 22 '12 at 20:14






        4




        4





        Does this mean garbage collection strategies correspond to weather?

        – DSM
        Aug 22 '12 at 20:18





        Does this mean garbage collection strategies correspond to weather?

        – DSM
        Aug 22 '12 at 20:18




        8




        8





        @DSM: Exactly :-) GC is the wind that blows away any balloons not tied down. :-)

        – Martijn Pieters
        Aug 22 '12 at 20:19





        @DSM: Exactly :-) GC is the wind that blows away any balloons not tied down. :-)

        – Martijn Pieters
        Aug 22 '12 at 20:19




        1




        1





        @user1404053: then you need a mutable balloon. A user-defined class, for example, instead of a string.

        – Martijn Pieters
        Aug 22 '12 at 20:23





        @user1404053: then you need a mutable balloon. A user-defined class, for example, instead of a string.

        – Martijn Pieters
        Aug 22 '12 at 20:23













        4














        Before your second print statement, store your new values into palin:



        palin = ["parrot", polly]





        share|improve this answer
























        • Anyway to do it without restoring the new value?

          – Flexo1515
          Aug 22 '12 at 20:07






        • 3





          @user1404053: Not the way you're asking. In Python strings are immutable, so there's no way to change the value in polly and therefore change it everywhere else. The line polly = "dead" is a rebinding operation rather than a mutating one

          – David Robinson
          Aug 22 '12 at 20:11
















        4














        Before your second print statement, store your new values into palin:



        palin = ["parrot", polly]





        share|improve this answer
























        • Anyway to do it without restoring the new value?

          – Flexo1515
          Aug 22 '12 at 20:07






        • 3





          @user1404053: Not the way you're asking. In Python strings are immutable, so there's no way to change the value in polly and therefore change it everywhere else. The line polly = "dead" is a rebinding operation rather than a mutating one

          – David Robinson
          Aug 22 '12 at 20:11














        4












        4








        4







        Before your second print statement, store your new values into palin:



        palin = ["parrot", polly]





        share|improve this answer













        Before your second print statement, store your new values into palin:



        palin = ["parrot", polly]






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Aug 22 '12 at 20:04









        girasquidgirasquid

        12k23652




        12k23652













        • Anyway to do it without restoring the new value?

          – Flexo1515
          Aug 22 '12 at 20:07






        • 3





          @user1404053: Not the way you're asking. In Python strings are immutable, so there's no way to change the value in polly and therefore change it everywhere else. The line polly = "dead" is a rebinding operation rather than a mutating one

          – David Robinson
          Aug 22 '12 at 20:11



















        • Anyway to do it without restoring the new value?

          – Flexo1515
          Aug 22 '12 at 20:07






        • 3





          @user1404053: Not the way you're asking. In Python strings are immutable, so there's no way to change the value in polly and therefore change it everywhere else. The line polly = "dead" is a rebinding operation rather than a mutating one

          – David Robinson
          Aug 22 '12 at 20:11

















        Anyway to do it without restoring the new value?

        – Flexo1515
        Aug 22 '12 at 20:07





        Anyway to do it without restoring the new value?

        – Flexo1515
        Aug 22 '12 at 20:07




        3




        3





        @user1404053: Not the way you're asking. In Python strings are immutable, so there's no way to change the value in polly and therefore change it everywhere else. The line polly = "dead" is a rebinding operation rather than a mutating one

        – David Robinson
        Aug 22 '12 at 20:11





        @user1404053: Not the way you're asking. In Python strings are immutable, so there's no way to change the value in polly and therefore change it everywhere else. The line polly = "dead" is a rebinding operation rather than a mutating one

        – David Robinson
        Aug 22 '12 at 20:11











        3














        When you put a string in a list, the list holds a copy of the string. It doesn't matter whether the string was originally a variable, a literal value, the result of a function call, or something else; by the time the list sees it, it's just a string value. Changing whatever generated the string later will never affect the list.



        If you want to store a reference to a value that will notice when that value changes, the usual mechanism is to use a list containing the "referenced" value. Applying that to your example, you wind up with a nested list:



        polly = ["alive"]
        palin = ["parrot", polly]
        print(palin)
        polly[0] = "dead"
        print(palin)





        share|improve this answer




























          3














          When you put a string in a list, the list holds a copy of the string. It doesn't matter whether the string was originally a variable, a literal value, the result of a function call, or something else; by the time the list sees it, it's just a string value. Changing whatever generated the string later will never affect the list.



          If you want to store a reference to a value that will notice when that value changes, the usual mechanism is to use a list containing the "referenced" value. Applying that to your example, you wind up with a nested list:



          polly = ["alive"]
          palin = ["parrot", polly]
          print(palin)
          polly[0] = "dead"
          print(palin)





          share|improve this answer


























            3












            3








            3







            When you put a string in a list, the list holds a copy of the string. It doesn't matter whether the string was originally a variable, a literal value, the result of a function call, or something else; by the time the list sees it, it's just a string value. Changing whatever generated the string later will never affect the list.



            If you want to store a reference to a value that will notice when that value changes, the usual mechanism is to use a list containing the "referenced" value. Applying that to your example, you wind up with a nested list:



            polly = ["alive"]
            palin = ["parrot", polly]
            print(palin)
            polly[0] = "dead"
            print(palin)





            share|improve this answer













            When you put a string in a list, the list holds a copy of the string. It doesn't matter whether the string was originally a variable, a literal value, the result of a function call, or something else; by the time the list sees it, it's just a string value. Changing whatever generated the string later will never affect the list.



            If you want to store a reference to a value that will notice when that value changes, the usual mechanism is to use a list containing the "referenced" value. Applying that to your example, you wind up with a nested list:



            polly = ["alive"]
            palin = ["parrot", polly]
            print(palin)
            polly[0] = "dead"
            print(palin)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 22 '12 at 20:12









            Mark ReedMark Reed

            65.6k989124




            65.6k989124























                1














                The list will contain values only, not references to variables as you would like. You could however store a lambda in the list, and have the lambda look up the value of your variable.



                >>> a = 'a'
                >>> list = ['a',lambda: a]
                >>> list[1]
                <function <lambda> at 0x7feff71dc500>
                >>> list[1]()
                'a'
                >>> a = 'b'
                >>> list[1]()
                'b'





                share|improve this answer
























                • Some more explanation: here lambda: a is basically a function that just returns the value stored in a. That's why you can use the command list[1](); it means you call the function stored in list[1]. (Also, appropriate gravatar, @Jonatan)

                  – Matthew Adams
                  Aug 22 '12 at 20:17











                • Quite right, thanks for the explanation. Also I had completely forgotten my avatar, haha!

                  – Jonatan
                  Aug 22 '12 at 20:20
















                1














                The list will contain values only, not references to variables as you would like. You could however store a lambda in the list, and have the lambda look up the value of your variable.



                >>> a = 'a'
                >>> list = ['a',lambda: a]
                >>> list[1]
                <function <lambda> at 0x7feff71dc500>
                >>> list[1]()
                'a'
                >>> a = 'b'
                >>> list[1]()
                'b'





                share|improve this answer
























                • Some more explanation: here lambda: a is basically a function that just returns the value stored in a. That's why you can use the command list[1](); it means you call the function stored in list[1]. (Also, appropriate gravatar, @Jonatan)

                  – Matthew Adams
                  Aug 22 '12 at 20:17











                • Quite right, thanks for the explanation. Also I had completely forgotten my avatar, haha!

                  – Jonatan
                  Aug 22 '12 at 20:20














                1












                1








                1







                The list will contain values only, not references to variables as you would like. You could however store a lambda in the list, and have the lambda look up the value of your variable.



                >>> a = 'a'
                >>> list = ['a',lambda: a]
                >>> list[1]
                <function <lambda> at 0x7feff71dc500>
                >>> list[1]()
                'a'
                >>> a = 'b'
                >>> list[1]()
                'b'





                share|improve this answer













                The list will contain values only, not references to variables as you would like. You could however store a lambda in the list, and have the lambda look up the value of your variable.



                >>> a = 'a'
                >>> list = ['a',lambda: a]
                >>> list[1]
                <function <lambda> at 0x7feff71dc500>
                >>> list[1]()
                'a'
                >>> a = 'b'
                >>> list[1]()
                'b'






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Aug 22 '12 at 20:11









                JonatanJonatan

                1,73411331




                1,73411331













                • Some more explanation: here lambda: a is basically a function that just returns the value stored in a. That's why you can use the command list[1](); it means you call the function stored in list[1]. (Also, appropriate gravatar, @Jonatan)

                  – Matthew Adams
                  Aug 22 '12 at 20:17











                • Quite right, thanks for the explanation. Also I had completely forgotten my avatar, haha!

                  – Jonatan
                  Aug 22 '12 at 20:20



















                • Some more explanation: here lambda: a is basically a function that just returns the value stored in a. That's why you can use the command list[1](); it means you call the function stored in list[1]. (Also, appropriate gravatar, @Jonatan)

                  – Matthew Adams
                  Aug 22 '12 at 20:17











                • Quite right, thanks for the explanation. Also I had completely forgotten my avatar, haha!

                  – Jonatan
                  Aug 22 '12 at 20:20

















                Some more explanation: here lambda: a is basically a function that just returns the value stored in a. That's why you can use the command list[1](); it means you call the function stored in list[1]. (Also, appropriate gravatar, @Jonatan)

                – Matthew Adams
                Aug 22 '12 at 20:17





                Some more explanation: here lambda: a is basically a function that just returns the value stored in a. That's why you can use the command list[1](); it means you call the function stored in list[1]. (Also, appropriate gravatar, @Jonatan)

                – Matthew Adams
                Aug 22 '12 at 20:17













                Quite right, thanks for the explanation. Also I had completely forgotten my avatar, haha!

                – Jonatan
                Aug 22 '12 at 20:20





                Quite right, thanks for the explanation. Also I had completely forgotten my avatar, haha!

                – Jonatan
                Aug 22 '12 at 20:20











                0














                You can't. Assignment to a bare name is Python always only rebinds the name, and you cannot customize or monitor this operation.



                What you can do is make polly a mutable object instead of a string, and mutate its value instead of rebinding the name. A simple example:



                >>> polly = ['alive']
                >>> items = ['parrot', polly]
                >>> items
                ['parrot', ['alive']]
                >>> polly[0] = 'dead'
                >>> items
                ['parrot', ['dead']]





                share|improve this answer




























                  0














                  You can't. Assignment to a bare name is Python always only rebinds the name, and you cannot customize or monitor this operation.



                  What you can do is make polly a mutable object instead of a string, and mutate its value instead of rebinding the name. A simple example:



                  >>> polly = ['alive']
                  >>> items = ['parrot', polly]
                  >>> items
                  ['parrot', ['alive']]
                  >>> polly[0] = 'dead'
                  >>> items
                  ['parrot', ['dead']]





                  share|improve this answer


























                    0












                    0








                    0







                    You can't. Assignment to a bare name is Python always only rebinds the name, and you cannot customize or monitor this operation.



                    What you can do is make polly a mutable object instead of a string, and mutate its value instead of rebinding the name. A simple example:



                    >>> polly = ['alive']
                    >>> items = ['parrot', polly]
                    >>> items
                    ['parrot', ['alive']]
                    >>> polly[0] = 'dead'
                    >>> items
                    ['parrot', ['dead']]





                    share|improve this answer













                    You can't. Assignment to a bare name is Python always only rebinds the name, and you cannot customize or monitor this operation.



                    What you can do is make polly a mutable object instead of a string, and mutate its value instead of rebinding the name. A simple example:



                    >>> polly = ['alive']
                    >>> items = ['parrot', polly]
                    >>> items
                    ['parrot', ['alive']]
                    >>> polly[0] = 'dead'
                    >>> items
                    ['parrot', ['dead']]






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Aug 22 '12 at 20:14









                    BrenBarnBrenBarn

                    162k20287289




                    162k20287289























                        0














                        The other answers have explained what's going on well.



                        This is one of the (several) problems that motivate the use of objects. For example, one might do this:



                        class Animal:
                        def __init__(self, aniType, name):
                        self.aniType = aniType
                        self.name = name
                        self.isAlive = True

                        def kill(self):
                        self.isAlive = False

                        def getName(self):
                        return self.name

                        def getType(self):
                        return self.aniType

                        def isLiving(self):
                        return self.isAlive


                        polly = Animal("parrot", "polly")

                        print(polly.getName()+' the '+polly.getType()+' is alive?')
                        print(polly.isLiving())

                        polly.kill()

                        print(polly.getName()+' the '+polly.getType()+' is alive?')
                        print(polly.isLiving())


                        It may look like a lot of code at first for a simple task, but objects are often the way to go for things like this, because they help keep everything organized.



                        Here's the output of that program:



                        polly the parrot is alive?
                        True
                        polly the parrot is alive?
                        False





                        share|improve this answer




























                          0














                          The other answers have explained what's going on well.



                          This is one of the (several) problems that motivate the use of objects. For example, one might do this:



                          class Animal:
                          def __init__(self, aniType, name):
                          self.aniType = aniType
                          self.name = name
                          self.isAlive = True

                          def kill(self):
                          self.isAlive = False

                          def getName(self):
                          return self.name

                          def getType(self):
                          return self.aniType

                          def isLiving(self):
                          return self.isAlive


                          polly = Animal("parrot", "polly")

                          print(polly.getName()+' the '+polly.getType()+' is alive?')
                          print(polly.isLiving())

                          polly.kill()

                          print(polly.getName()+' the '+polly.getType()+' is alive?')
                          print(polly.isLiving())


                          It may look like a lot of code at first for a simple task, but objects are often the way to go for things like this, because they help keep everything organized.



                          Here's the output of that program:



                          polly the parrot is alive?
                          True
                          polly the parrot is alive?
                          False





                          share|improve this answer


























                            0












                            0








                            0







                            The other answers have explained what's going on well.



                            This is one of the (several) problems that motivate the use of objects. For example, one might do this:



                            class Animal:
                            def __init__(self, aniType, name):
                            self.aniType = aniType
                            self.name = name
                            self.isAlive = True

                            def kill(self):
                            self.isAlive = False

                            def getName(self):
                            return self.name

                            def getType(self):
                            return self.aniType

                            def isLiving(self):
                            return self.isAlive


                            polly = Animal("parrot", "polly")

                            print(polly.getName()+' the '+polly.getType()+' is alive?')
                            print(polly.isLiving())

                            polly.kill()

                            print(polly.getName()+' the '+polly.getType()+' is alive?')
                            print(polly.isLiving())


                            It may look like a lot of code at first for a simple task, but objects are often the way to go for things like this, because they help keep everything organized.



                            Here's the output of that program:



                            polly the parrot is alive?
                            True
                            polly the parrot is alive?
                            False





                            share|improve this answer













                            The other answers have explained what's going on well.



                            This is one of the (several) problems that motivate the use of objects. For example, one might do this:



                            class Animal:
                            def __init__(self, aniType, name):
                            self.aniType = aniType
                            self.name = name
                            self.isAlive = True

                            def kill(self):
                            self.isAlive = False

                            def getName(self):
                            return self.name

                            def getType(self):
                            return self.aniType

                            def isLiving(self):
                            return self.isAlive


                            polly = Animal("parrot", "polly")

                            print(polly.getName()+' the '+polly.getType()+' is alive?')
                            print(polly.isLiving())

                            polly.kill()

                            print(polly.getName()+' the '+polly.getType()+' is alive?')
                            print(polly.isLiving())


                            It may look like a lot of code at first for a simple task, but objects are often the way to go for things like this, because they help keep everything organized.



                            Here's the output of that program:



                            polly the parrot is alive?
                            True
                            polly the parrot is alive?
                            False






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Aug 22 '12 at 20:35









                            Matthew AdamsMatthew Adams

                            5,45031841




                            5,45031841






























                                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.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f12080552%2fpython-list-doesnt-reflect-variable-change%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

                                MongoDB - Not Authorized To Execute Command

                                How to fix TextFormField cause rebuild widget in Flutter

                                in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith