Search code examples
pythonlistvariables

How to update a list of variables in python?


This is an aggravating issue that I've come into whilst programming in python. The user can append various variables to a list however, this list when accessed later on will still display the same results as when first assigned. e.g below

a=1
b=2
list = [a,b] #user defined order
print list # 1,2
a=2
print list # prints 1,2

I need list to print out 2,2. However i cannot find out a way to DYNAMICALLY update the list to accommodate ANY order of the variables (many ways are hard coding which i've seen online such as assigning list = [a,b] when needed to update however i dont know if its b,a or a,b)

Help would be much appreciated. Thank you

Edit : My question is different due to being about varaibles that need to be dynamically updated in a list rather than simply changing a list item.


Solution

  • It's not possible if you store immutable items in a list, which Python integers are, so add a level of indirection and use mutable lists:

    a,b,c,d = [1],[2],[3],[4]
    L = [d,b,a,c] # user-defined order
    print L
    a[0] = 5
    print L
    

    Output:

    [[4], [2], [1], [3]]
    [[4], [2], [5], [3]]
    

    This has the feel of an X-Y Problem, however. Describing the problem you are solving with this solution may elicit better solutions.