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.

2
  • Possible duplicate of Passing a list element as reference Commented Dec 30, 2016 at 15:40
  • 2
    Don't use list as a variable name, python has a list type which this would hide. Commented Dec 30, 2016 at 16:10

7 Answers 7

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
Sign up to request clarification or add additional context in comments.

7 Comments

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 :(
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?
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
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?
@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!
|
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.

1 Comment

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 ! :)
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

Comments

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

4 Comments

Of course, this means you can't do math on your objects without writing a whole bunch of other code.
Doing maths is not mentiooned anywhere by the OP. Your comment, while true, is therefore irrelevant. Don't vote me down for it.
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.
it answers the question rather than conjectures.
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

Comments

0

You can define a function:\

a, b = 1, 2

def list_():
   return [a, b]

list_() # [1, 2]

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.