5

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.

john hon
  • 103
  • 2
  • 2
  • 7

7 Answers7

7

you need to update the list and not the variable:

a = 1
b = 2
lst = [a, b]  # the list now stores the references a and b point to
              # changing a later on has no effect on this!  
lst[0] = 2

and please do not use list as variable name! this is a keyword built-in type in python and overwriting it is a very bad idea!

if you only know the value of the element in the list (and this value is unique) you could do this:

old_val = 2
new_val = 3

lst[lst.index(old_val)] = new_val
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • that is my issue, i CANNOT simply state lst = [a,b] because the order is unknown so as much as i want to, i cannot do that :( – john hon Dec 31 '16 at 01:36
  • then your problem is not the same as the one you present in the question: there you put `a` first in the list and then want to change `a` (the first element in the list). what *is* the question then? – hiro protagonist Dec 31 '16 at 07:55
  • sorry for the confusion. a could be the nth element of the list and the list could be defined in any order e.g [a,b...],[b,a....] etc. so my question is how to a change a variable that is inside a list and then get it to reflect this later? thanks for your help so far – john hon Jan 01 '17 at 14:48
  • hello @hiroprotagonist, if the list if list of pandas dataframes and I want to change actual value of dataframe, how will I change this equation? I dont want value to just change in list (lst) but the actual values in dataframes also change? Any ideas? – rishi jain May 31 '20 at 08:04
  • @rishijain sorry, it is a bit hard to understand what you really want. why don't you make it a real question so people more proficient than me can answer! good luck! – hiro protagonist May 31 '20 at 08:14
  • @hiroprotagonist, in the above example we have a =1 and b =2, and both are variables and lst is a list of a and b. In case, a and b are both dataframes and lst is a list of dataframes, how can I assign new values of a and b to lst, such that the actual values of a and b change? – rishi jain May 31 '20 at 08:19
  • if you change your dataframe inplace, the change should be reflected in the original variables as well. see e.g. https://stackoverflow.com/questions/47245583/pandas-manipulating-a-dataframe-inplace-vs-not-inplace-inplace-true-vs-false . – hiro protagonist May 31 '20 at 08:28
4

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.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • sigh sadly it was sorta like an XY problem, however i found another case where i did actually need this so your efforts were not wasted ! :) – john hon Jan 02 '17 at 07:47
2

Why don't you use dictionary??

With dictionary:

_dict = {}
_dict["a"] = 1
_dict["b"] = 2
print _dict["a"] # prints 1

Now if you want to set and get value of variable "a":

_dict["a"] = 2
print _dict["a"] # prints 2
0

At the assignment 'a=1' an integer object is created with the value 1. That object is added to your list. At the second assignment (a=2) a new object is created, but the old one still is in the list, its value unchanged. That is what you see.

To change this behaviour, the value of the object must be changed. Ints are immutable in Python, meaning that exactly this, i.e. changing the value, is not possible. You'll have to define your own and then change its value. For example:

class MyInt(object):

    def __init__(self, value):
        self.setValue(value)

    def setValue(self, value):
        self.value = value

    def __repr__(self):
        return str(self.value)

a=MyInt(1)
print(dir(a))
b=2
list = [a,b] #user defined order
print (list) # 1,2
a.setValue(2)
print (list) # prints 2,2
user508402
  • 496
  • 1
  • 4
  • 19
  • Of course, this means you can't do math on your objects without writing a whole bunch of other code. – ThisSuitIsBlackNot Dec 30 '16 at 16:26
  • 1
    Doing maths is not mentiooned anywhere by the OP. Your comment, while true, is therefore irrelevant. Don't vote me down for it. – user508402 Dec 30 '16 at 18:19
  • When somebody fills a list with numbers, they will almost certainly want to manipulate those numbers somehow. With your solution, you can't even compare the list items to other numbers to see if they're equal! I don't think that's a very useful approach. – ThisSuitIsBlackNot Dec 30 '16 at 18:30
  • it answers the question rather than conjectures. – user508402 Dec 30 '16 at 18:56
0

It is not clean but a work around trick , you can assign the value of a is a single element list

a = [1]
b = 2

So when you assign them to a list:

lst = [a,b]

and change the value of a by calling its 0th element:

a[0] = 2

it will also change the referenced list that is a

print(lst)
#[[2],2]

likewise if you place the value in the list:

lst[0][0] = 2
print(a[0])
#2
Yodawgz0
  • 37
  • 5
0

You can define a function:\

a, b = 1, 2

def list_():
   return [a, b]

list_() # [1, 2]

a = 2
list_() # [2, 2]
0

What I've done to get around this is just make a function to update/redefine the list that I can call after updating variables. Kind of dirty but it works and is fast.

def updateList():
   lst = [a,b]

This will make the list refresh its contents with the newest variable values, allowing the following:

a=1
b=2
list = [a,b]
a=2
updateList()
print(lst)

Depending on how often you need to update the elements this may help.