Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
john hon Avatar asked Dec 30 '16 15:12

john hon


2 Answers

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
like image 188
hiro protagonist Avatar answered Oct 14 '22 05:10

hiro protagonist


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.

like image 39
Mark Tolonen Avatar answered Oct 14 '22 07:10

Mark Tolonen