Home > Blockchain >  Can I link two variables such that one is double of another in python?
Can I link two variables such that one is double of another in python?

Time:12-18

So basically I have two lists a and b and have defined them like a=b=[10] so changing one will change the other-

a=b=[10]
a[0] =1
a
>>>[11]
b
>>>[11]

Is there a way to do this but instead make it give double of the variable? Desired output -

a=b=[10]
#some code
a
>>>[10]
b
>>>[20]

CodePudding user response:

You can create a new class that inherits from list and create a property that returns the modified values:

class new_list(list):
    @property
    def double(self):
        return [i * 2 for i in self]

        
a = new_list([10])

a.append(20)
a.append(30)
print(a, a.double)
[10, 20, 30] [20, 40, 60]

The advantage with this approach is that you still be able to use all methods from list directly.

CodePudding user response:

I'm not sure if I get what you're trying to do correctly, but something like this should work.

prop = property(lambda self: self.a * 2)
# Dynamically creating a class with a default value for `a` and `b`
Class = type('ClassName', (object,), {"a": 0, "b": prop})

c = Class()
c.a = [10]
print(c.a, c.b)  # ([10], [10, 10])

CodePudding user response:

with a=b=[0] you don't actually have two lists. The assignment just copies the reference to the list, not the actual list, so both liat 'a' and list 'b' refer to the same list after the assignment.

a=b=[10]
print(a) // [10]
b = list(a)[0] * 2 
a[0]  = 1

print(a) // [11]
print(b) // [20]

To actually copy a into b you have various option simplest one would be using using the built in list() function to make a actual copy . Thank You.

CodePudding user response:

Because a=b=[10] is equal to b=[10];a=b so they are the same thing with only one instance. You can just

b=[a[0]*2] 

or

b=[x*2 for x in a]
  • Related